以下是一个简单的示例,展示了 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"];