深入理解 KVO-KVO 的实现细节

时间:2024-07-09 20:49:07

以下是一个简单的示例,展示了 KVO 的一些底层实现细节:

@interface Person : NSObject
@property (nonatomic, assign) int age;
@end

@implementation Person
@end

Person *person = [[Person alloc] init];
NSLog(@"Original class: %@", object_getClass(person)); // 输出原始类

[person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
NSLog(@"Class after adding observer: %@", object_getClass(person)); // 输出动态子类

[person setAge:30];
[person removeObserver:self forKeyPath:@"age"];