iOS.KVC.setValue:forKey:
2014-08-27 22:58
357 查看
Foundation Framework 定义了 NSObject(NSKeyValueCoding),
该接口的说明
1. 先在message receiver的class中搜索方法 -set<Key>:
2. 如果1中未找到,则在class中以此搜索 _<key>, _is<key>, <key>, is<Key> 实例变量
3. 如果2中未找到,则调用方法 -setValue:forUndefinedKey:, 而该方法默认的实现是抛出
异常 NSUndefinedKeyException
接下来问题来,那么在iOS SDK中那么多framework,那么多的class,那么哪些class覆盖了NSObject
对-setValue:forUndefinedKey:的默认实现呢?
log的输出为:defaultImp: 0x125dc84, animationImp: 0x10d5ca, viewImp: 0x125dc84
可见UIView并没有覆盖NSObject的默认实现,即一个class和NSObject 类 对以下调用的返回值一致
所以在使用 -setValue:forKey:时需要用try-catch 来wrap对这个方法的调用。
- (void)setValue:(id)value forKey:(NSString *)key;
该接口的说明
1. 先在message receiver的class中搜索方法 -set<Key>:
2. 如果1中未找到,则在class中以此搜索 _<key>, _is<key>, <key>, is<Key> 实例变量
3. 如果2中未找到,则调用方法 -setValue:forUndefinedKey:, 而该方法默认的实现是抛出
异常 NSUndefinedKeyException
接下来问题来,那么在iOS SDK中那么多framework,那么多的class,那么哪些class覆盖了NSObject
对-setValue:forUndefinedKey:的默认实现呢?
IMP animationImp = [CAAnimation instanceMethodForSelector:@selector(setValue:forUndefinedKey:)]; IMP defaultImp = [NSObject instanceMethodForSelector:@selector(setValue:forUndefinedKey:)]; IMP viewImp = [UIView instanceMethodForSelector:@selector(setValue:forUndefinedKey:)]; NSLog(@"defaultImp: %p, animationImp: %p, viewImp: %p", defaultImp, animationImp, viewImp);
log的输出为:defaultImp: 0x125dc84, animationImp: 0x10d5ca, viewImp: 0x125dc84
可见UIView并没有覆盖NSObject的默认实现,即一个class和NSObject 类 对以下调用的返回值一致
instanceMethodForSelector:@selector(setValue:forUndefinedKey:)
所以在使用 -setValue:forKey:时需要用try-catch 来wrap对这个方法的调用。
相关文章推荐
- iOS KVC原理与setValue/valueForKey 崩溃解决
- iOS: setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.
- iOS: setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.
- iOS -setValue:forKey:和-setObject: forKey区别
- iOS开发中setObject:ForKey和setValue:ForKey的用法和区别
- 从[id setValue: forKey:]了解KVC
- iOS KVC valueForKeyPath学习心得
- iOS开发之NSDictionary里setValue:forKey与setObject:forKey、objectForKey与valueForKey的差异
- iOS - (void)setValue:(id)value forKey:(NSString *)key方法~实现
- IOS开发之NSDictionary里setValue:forKey与setObject:forKey、objectForKey与valueForKey的差异
- iOS - xib死活连不上代码问题/[<NSObject 0x1702023e0> setValue:forUndefinedKey:]: this class is not key
- iOS Xcode 6报错:setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key v
- KVC之-setValue:forKey:方法实现原理与验证
- iOS could not set nil as the value for the key
- IOS开发之NSDictionary里setValue:forKey与setObject:forKey、objectForKey与valueForKey的差异
- IOS开发之NSDictionary里setValue:forKey与setObject:forKey、objectForKey与valueForKey的差异
- iOS开发66-setValue:forKey:和 setObject:forKey:的区别
- iOS [<NSObject 0x170204110> setValue:forUndefineKey:]: this class is not key value coding-compliant
- 从[id setValue: forKey:]了解KVC
- iOS- 报错(崩)[< > setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key