我有一个 tableView(这是一个包含大约 11 个字段的表单)、tableViewController 和一个我用来作为表单模型的类的实例。tableView 控制器使用 KVO 对模型的更改进行更新。因此,与其有 11 个 IF ELSE 语句来比较我的观察值中的 keypath 字符串,不如像这样的关键方法 -
- (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...
}
我虽然有这样的东西会更干净,只需遵循更新方法的命名约定
// 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];
}
我不确定这是否被认为是好的做法。