Using KVO with custom UITableViewCell and CoreData
I've read over a ton of documentation and tutorials about KVO but I haven't found any that I've been able to abstract for my application. I have a table view that uses a custom UITableViewCell class to provide an interface for turning options on/off. The cell has a UISwitch that I would like to "bind" to my model's boolean properties. I'd like it that when the cell is rendered it should set the on property of the control appropriately for the managed object and when I flip that switch control, the model object will update to the new value.
I started working on it but the first step of what I thought was appropriate is not working.
[switchControl addObserver:self
forKeyPath:@"on"
options:0
context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)c开发者_如何学Context
{
NSLog(@"value changed");
}
Try this:
[switchControl addObserver:self
forKeyPath:@"on"
options:NSKeyValueObservingOptionNew
context:NULL];
Instead of addObserver you can use addTarget as below:
[switchControl addTarget:self action:@selector(photoSwitchChanged:)forControlEvents:UIControlEventValueChanged];
where target function is defined as follows:
- (void)photoSwitchChanged:(UISwitch*)switch {
}
精彩评论