- 注册KVO:
在需要监听属性变化的类中,通常在
init
方法或其他合适的初始化位置进行注册。假设我们有一个被监听的类Person
,有一个属性name
。
// 假设Person类的定义
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
@implementation Person
@end
// 监听类
@interface ViewController : UIViewController
@property (nonatomic, strong) Person *person;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc] init];
// 注册KVO
[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}
- 实现监听方法:
在监听类中实现
observeValueForKeyPath:ofObject:change:context:
方法。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"name"] && object == self.person) {
NSString *newName = change[NSKeyValueChangeNewKey];
NSLog(@"The name has changed to: %@", newName);
}
}
- 移除KVO:
通常在
dealloc
方法中移除KVO,以避免内存泄漏。
- (void)dealloc {
[self.person removeObserver:self forKeyPath:@"name"];
}