@interface Person : NSObject
@property (nonatomic, strong, nullable) NSString *name;
@end
@implementation Person
@end
@interface ViewController ()
@property (nonatomic, strong) Person *p1;
@property (nonatomic, strong) Person *p2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.p1 = [[Person alloc] init];
self.p2 = [[Person alloc] init];
self.p1.name = @"Tom";
NSLog(@"before kvo --- p2: %s", object_getClassName(self.p2));
[self.p2 addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
NSLog(@"after kvo --- p2: %s", object_getClassName(self.p2));
self.p2.name = @"Jerry";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"name"]) {
NSLog(@"new name: %@", change[NSKeyValueChangeNewKey]);
}
}
@end
// 输出
before kvo --- p2: Person
after kvo --- p2: NSKVONotifying_Person
new name: Jerry
swizzling
最新推荐文章于 2020-07-31 00:47:22 发布