swizzling

@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
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页