Ios 在使用KVO时,这是否被视为良好的编程实践

Ios 在使用KVO时,这是否被视为良好的编程实践,ios,objective-c,design-patterns,key-value-observing,Ios,Objective C,Design Patterns,Key Value Observing,我有一个tableView(这是一个大约有11个字段的表单)、tableViewController和一个类的实例,我用它作为表单的模型。tableView控制器使用KVO对模型进行更新。因此,在我的observe value for key方法中没有11条IF-ELSE语句来比较keypath字符串- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *

我有一个tableView(这是一个大约有11个字段的表单)、tableViewController和一个类的实例,我用它作为表单的模型。tableView控制器使用KVO对模型进行更新。因此,在我的observe value for key方法中没有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];
}
//KVO更新方法名称遵循命名约定“更新”。
//密钥路径的第一个字符应大写。
-(void)observeValueForKeyPath:(NSString*)对象的键路径:(id)对象更改:(NSDictionary*)更改上下文:(void*)上下文
{
NSString*firstCharacterOfKeyPath=[keyPath substringToIndex:1];
NSString*大写的firstCharacterOfKeyPath=[firstCharacterOfKeyPath大写字符串];
NSRange firstCharacterRange=NSMakeRange(0,1);
NSString*CapitalizedKeyPath=[keyPath StringByReplacingCharactersRange:firstCharacterRange with String:CapitalizedFirstCharacterOfKeyPath];
NSString*updateSelectorString=[[NSString alloc]initWithFormat:@“update%@”,大写键路径];
SEL updateSelector=NSSelectorFromString(updateSelectorString);
[自执行选择器:更新选择器];
}

我不确定这是否被视为良好做法。

我没有看到您的代码中存在任何真正的问题,但是我会添加检查
self
是否响应选择器,以防止进一步崩溃:

if ([self respondsToSelector:updateSelector])
{
    [self performSelector:updateSelector];
}
但就个人而言,我并不真正喜欢KVO方法。我不想说它不好,但它可能会产生不必要的错误。也就是说,您应该记住如何正确地删除观察者,对于UITableView来说,这并不是一件小事

我建议在这里使用委托方法,尽管它看起来有点复杂,但对我来说,它听起来更可靠