iOS下KVO的使用以及一些实现细节

来源:互联网 发布:怎样举报淘宝店铺 编辑:程序博客网 时间:2024/05/20 20:44
KVO的是Key Value Observe的缩写,中文是键值观察。这是一个典型的观察者模式,观察者在键值改变时会得到通知。iOS中有个Notification的机制,也可以获得通知,但这个机制需要有个Center,相比之下KVO更加简洁而直接。
      KVO的使用也很简单,就是简单的3步。
      1.注册需要观察的对象的属性addObserver:forKeyPath:options:context:
      2.实现observeValueForKeyPath:ofObject:change:context:方法,这个方法当观察的属性变化时会自动调用
      3.取消注册观察removeObserver:forKeyPath:context:

      不多说了,上代码:
[html] view plaincopy
  1. @interface myPerson : NSObject  
  2. {  
  3.     NSString *_name;  
  4.     int      _age;  
  5.     int      _height;  
  6.     int      _weight;  
  7. }  
  8. @end  
  9.   
  10. @interface testViewController : UIViewController  
  11. @property (nonatomic, retain) myPerson *testPerson;  
  12.   
  13. - (IBAction)onBtnTest:(id)sender;  
  14. @end  
  15.   
  16. - (void)testKVO  
  17. {  
  18.     testPerson = [[myPerson alloc] init];  
  19.       
  20.     [testPerson addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew context:nil];  
  21. }  
  22.   
  23. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
  24. {  
  25.     if ([keyPath isEqualToString:@"height"]) {  
  26.         NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]);  
  27.     } else {  
  28.         [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];  
  29.     }  
  30. }  
  31.   
  32. - (IBAction)onBtnTest:(id)sender {  
  33.     int h = [[testPerson valueForKey:@"height"] intValue];      
  34.     [testPerson setValue:[NSNumber numberWithInt:h+1] forKey:@"height"];  
  35.     NSLog(@"person height=%@", [testPerson valueForKey:@"height"]);  
  36. }  
  37.   
  38. - (void)dealloc  
  39. {  
  40.     [testPerson removeObserver:self forKeyPath:@"height" context:nil];  
  41.     [super dealloc];  
  42. }  
      第一段代码声明了myPerson类,里面有个_height的属性。在testViewController有一个testPerson的对象指针。
      在testKVO这个方法里面,我们注册了testPerson这个对象height属性的观察,这样当testPerson的height属性变化时,会得到通知。在这个方法中还通过NSKeyValueObservingOptionNew这个参数要求把新值在dictionary中传递过来。
      重写了observeValueForKeyPath:ofObject:change:context:方法,这个方法里的change这个NSDictionary对象包含了相应的值。
      需要强调的是KVO的回调要被调用,属性必须是通过KVC的方法来修改的,如果是调用类的其他方法来修改属性,这个观察者是不会得到通知的。

       因为Cocoa是严格遵循MVC模式的,所以KVO在观察Modal的数据变化时很有用。那么KVO是怎么实现的呢,苹果官方文档上说的比较简单:“Automatic key-value observing is implemented using a technique called isa-swizzling.”
       “When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.”
        就是说在运行时会生成一个派生类,在这个派生类中重写基类中任何被观察属性的 setter 方法,用来欺骗系统顶替原先的类。

        继续观察一下代码:
[html] view plaincopy
  1. @interface myPerson : NSObject  
  2. {  
  3.     NSString *_name;  
  4. }  
  5.   
  6. @property (nonatomic)int height;  
  7. @property (nonatomic)int weight;  
  8. @property (nonatomic)int age;  
  9. @end  
  10.   
  11. @implementation myPerson  
  12. @synthesize height, weight, age;  
  13. @end  
  14.   
  15. #import "objc/runtime.h"  
  16. static NSArray * ClassMethodNames(Class c)  
  17. {  
  18.     NSMutableArray * array = [NSMutableArray array];  
  19.       
  20.     unsigned int methodCount = 0;  
  21.     Method * methodList = class_copyMethodList(c, &methodCount);  
  22.     unsigned int i;  
  23.     for(i = 0; i < methodCount; i++) {  
  24.         [array addObject: NSStringFromSelector(method_getName(methodList[i]))];  
  25.     }  
  26.       
  27.     free(methodList);  
  28.       
  29.     return array;  
  30. }  
  31.   
  32. static void PrintDescription(NSString * name, id obj)  
  33. {  
  34.     NSString * str = [NSString stringWithFormat:  
  35.                       @"\n\t%@: %@\n\tNSObject class %s\n\tlibobjc class %s\n\timplements methods <%@>",  
  36.                       name,  
  37.                       obj,  
  38.                       class_getName([obj class]),  
  39.                       class_getName(obj->isa),  
  40.                       [ClassMethodNames(obj->isa) componentsJoinedByString:@", "]];  
  41.     NSLog(@"%@", str);  
  42. }  
  43.   
  44. - (void)testKVOImplementation  
  45. {  
  46.     myPerson * anything = [[myPerson alloc] init];  
  47.     myPerson * hObserver = [[myPerson alloc] init];  
  48.     myPerson * wObserver = [[myPerson alloc] init];  
  49.     myPerson * hwObserver = [[myPerson alloc] init];  
  50.     myPerson * normal = [[myPerson alloc] init];  
  51.       
  52.     [hObserver addObserver:anything forKeyPath:@"height" options:0 context:NULL];  
  53.     [wObserver addObserver:anything forKeyPath:@"weight" options:0 context:NULL];  
  54.       
  55.     [hwObserver addObserver:anything forKeyPath:@"height" options:0 context:NULL];  
  56.     [hwObserver addObserver:anything forKeyPath:@"weight" options:0 context:NULL];  
  57.       
  58.     PrintDescription(@"normal", normal);  
  59.     PrintDescription(@"hObserver", hObserver);  
  60.     PrintDescription(@"wObserver", wObserver);  
  61.     PrintDescription(@"hwOBserver", hwObserver);  
  62.       
  63.     NSLog(@"\n\tUsing NSObject methods, normal setHeight: is %p, overridden setHeight: is %p\n",  
  64.           [normal methodForSelector:@selector(setHeight:)],  
  65.           [hObserver methodForSelector:@selector(setHeight:)]);  
  66.     NSLog(@"\n\tUsing libobjc functions, normal setHeight: is %p, overridden setHeight: is %p\n",  
  67.           method_getImplementation(class_getInstanceMethod(object_getClass(normal),  
  68.                                                            @selector(setHeight:))),  
  69.           method_getImplementation(class_getInstanceMethod(object_getClass(hObserver),  
  70.                                                            @selector(setHeight:))));  
  71. }  
        略微改写了一下myPerson,age/height/weight两个属性增加了getter/setter方法,然后运用runtime的方法,打印相应的内容,运行的log如下:
2013-11-02 20:36:22.391 test[2438:c07] 
normal: <myPerson: 0x886b840>
NSObject class myPerson
libobjc class myPerson
implements methods <weight, setWeight:, age, setAge:, height, setHeight:>
2013-11-02 20:36:22.393 test[2438:c07] 
hObserver: <myPerson: 0x886b7e0>
NSObject class myPerson
libobjc class NSKVONotifying_myPerson
implements methods <setWeight:, setHeight:, class, dealloc, _isKVOA>
2013-11-02 20:36:22.393 test[2438:c07] 
wObserver: <myPerson: 0x886b800>
NSObject class myPerson
libobjc class NSKVONotifying_myPerson
implements methods <setWeight:, setHeight:, class, dealloc, _isKVOA>
2013-11-02 20:36:22.393 test[2438:c07] 
hwOBserver: <myPerson: 0x886b820>
NSObject class myPerson
libobjc class NSKVONotifying_myPerson
implements methods <setWeight:, setHeight:, class, dealloc, _isKVOA>
2013-11-02 20:36:22.394 test[2438:c07] 
Using NSObject methods, normal setHeight: is 0x37e0, overridden setHeight: is 0x37e0
2013-11-02 20:36:22.394 test[2438:c07] 
Using libobjc functions, normal setHeight: is 0x37e0, overridden setHeight: is 0xb859e0
  
        从log信息可以清楚的看到派生了一个NSKVONotifying_XXX的类,这个派生类集合了每个KVO观察者的信息,所以这个派生类可以全局公用。
        另外,观察原来类的方法和派生类的方法,每个被观察的属性都重写了,比如:setWeight:方法和setHeight:方法,没被观察的属性都没有重新生成,比如:height:方法、weight:方法、age:方法和setAge:方法。
0 0
原创粉丝点击