@interface ObjTest1 : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *path;
@end
@implementation ObjTest1
@end
@interface ObjTest2 : NSObject
@end
@implementation ObjTest2
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"===== change %@",change);
}
@end
//测试,调用
ObjTest1 *obj1 = [ObjTest1 new];
ObjTest2 *obj2 = [ObjTest2 new];
obj1.name = @"aaa";
[obj1 addObserver:obj2 forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
obj1.name = @"bbb";
id info = obj1.observationInfo;
id info1 = [info valueForKey:@"_observances"];
id info2 = [info1 valueForKey:@"_property"];
id info3 = [info2 valueForKey:@"_keyPath"];
NSLog(@"====== 0 %@",info);
NSLog(@"====== 1 %@",info1);
NSLog(@"====== 2 %@",info2);
NSLog(@"====== 3 %@",info3);
//打印结果
2019-08-02 14:57:23.577722+0800 ObserverTest[9223:780503] ====== 0 <NSKeyValueObservationInfo 0x6000017168c0> (
<NSKeyValueObservance 0x600001953ab0: Observer: 0x60000154e3b0, Key path: name, Options: <New: YES, Old: YES, Prior: NO> Context: 0x0, Property: 0x6000019537e0>
)
2019-08-02 14:57:23.577872+0800 ObserverTest[9223:780503] ====== 1 (
"<NSKeyValueObservance 0x600001953ab0: Observer: 0x60000154e3b0, Key path: name, Options: <New: YES, Old: YES, Prior: NO> Context: 0x0, Property: 0x6000019537e0>"
)
2019-08-02 14:57:23.577994+0800 ObserverTest[9223:780503] ====== 2 (
"<NSKeyValueUnnestedProperty: Container class: ObjTest1, Key: name, isa for autonotifying: NSKVONotifying_ObjTest1, Key paths of directly and indirectly affecting properties: none>"
)
2019-08-02 14:57:23.578077+0800 ObserverTest[9223:780503] ====== 3 (
name
)
如上面测试 结论 用上面这些私有字段可以检测 被观察者 被观察的 keyPath。
若添加两次 “name” 的观察,测试 info3 就有两个 name。
移除观察者前,可以用这个判断是否添加了 这个keyPath 的观察者!