I have a tableView (which is a form with around 11 fields), tableViewController and a instance of a class I'm using to be the model for the form. The tableView controller is updated with changes to the model using KVO. So rather than having 11 IF ELSE statements that compare the keypath string in my observe value for key method like this -
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keypath isEqualToSTring:@"name"]){
[self updateName];
}
else if([keypath isEqualToSTring:@"age"]){
[self updateAge];
}
etc,etc,etc...
}
I though it would be cleaner to have something like this and just follow a naming convention for the update methods
// KVO update methods name follow the naming convention "update<keypath>".
// The first character of the keypath should be capitalised.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSString * firstCharacterOfKeyPath = [keyPath substringToIndex:1];
NSString * capitalisedFirstCharacterOfKeyPath = [firstCharacterOfKeyPath uppercaseString];
NSRange firstCharacterRange = NSMakeRange(0, 1);
NSString * capitalisedKeyPath = [keyPath stringByReplacingCharactersInRange:firstCharacterRange withString:capitalisedFirstCharacterOfKeyPath];
NSString * updateSelectorString = [[NSString alloc] initWithFormat:@"update%@",capitalisedKeyPath];
SEL updateSelector = NSSelectorFromString(updateSelectorString);
[self performSelector:updateSelector];
}
I'm not sure if this would be considered good practice or not.
I don't see any real issues in your code, however I'd have added check if self
responds to selector, to prevent further crashes:
if ([self respondsToSelector:updateSelector])
{
[self performSelector:updateSelector];
}
But personally, I don't really like KVO approach. I don't want to say that it's bad, but it could produce unwanted errors. I.e. you should remember about removing observers properly, which could be not really trivial in case of UITableView.
I'd recommend to use delegate methods here, even though it looks a bit more complex, but for me it sounds more reliable.