Today encountered a little bit about KVO, tangled for a half day. The result is out.
Requirement: Monitor the change of UITableView data, once change, refresh UITableView.
It is obvious to use the KVO. Data is put into
@property (nonatomic, strong) nsmutablearray* data;
At first I was doing this:
1, register for monitoring
-(void) Viewdidload {
[Super Viewdidload];
KVO Monitoring of data changes
[Self addobserver:self forkeypath:@ "data" options:0 Context:nil];
}
2, rewrite: ObserveValueForKeyPath:ofObject:change:context:
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context {
Refresh
[Self.tableview Reloaddata];
}
3, change the value of self.data ...
[Self.data addobject:[nsstring stringwithformat:@ "Hello"];
4, RESULTS: NO response!!!!
It took a long time to find a little something. In Kvo, there are two types: manual notification and automatic notification. The above notification is not responding because this is a manual notification, so when the attribute changes, add both methods before and after: Willchangevalueforkey:, Didchangevalueforkey: In automatic notifications, these two methods can be used without adding them.
In the third section, change to the following method is OK.
[Self willchangevalueforkey:@ "data"];
[Self.data addobject:[nsstring stringwithformat:@ "%d", Indexpath.row]];
[Self didchangevalueforkey:@ "data"];
For specific reasons, look at the documentation.
Of course, if you need to change the automatic notification of an attribute to the demand of a wonderful manual notification in your app. It's not going to work. Rewrite the following NSObject class method is OK:
Automaticallynotifiesobserversforkey.biru:
+ (BOOL) Automaticallynotifiesobserversforkey: (NSString *) key{
Change automatic notification of the BackgroundColor property to manual notification
if ([Key isequaltostring:@ "BackgroundColor"]) {
return NO;
}
return [Super Automaticallynotifiesobserversforkey:key];
}
The thing that kvo in IOS