MST

星途 面试题库

面试题:Objective-C中KVO属性变化监听基础使用

请描述在Objective-C中如何通过KVO监听一个对象的某个属性变化。请举例说明具体的步骤,包括如何注册KVO、实现监听方法以及移除KVO。
15.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 注册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];
}
  1. 实现监听方法: 在监听类中实现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);
    }
}
  1. 移除KVO: 通常在dealloc方法中移除KVO,以避免内存泄漏。
- (void)dealloc {
    [self.person removeObserver:self forKeyPath:@"name"];
}