zoukankan      html  css  js  c++  java
  • iOS.KVC.setValue:forKey:

    Foundation Framework 定义了 NSObject(NSKeyValueCoding),

    - (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:的默认实现呢?

    1 IMP animationImp = [CAAnimation instanceMethodForSelector:@selector(setValue:forUndefinedKey:)];
    2 
    3 IMP defaultImp = [NSObject instanceMethodForSelector:@selector(setValue:forUndefinedKey:)];
    4 
    5 IMP viewImp = [UIView instanceMethodForSelector:@selector(setValue:forUndefinedKey:)];
    6 
    7 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对这个方法的调用。

    ---
  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/cwgk/p/3940530.html
Copyright © 2011-2022 走看看