MST
星途 面试题库

面试题:Objective-C中通知中心机制里如何添加和移除观察者

请简述在Objective-C的通知中心机制里,如何使用代码添加一个观察者来监听特定通知,以及在不再需要监听时怎样移除这个观察者,并给出相应的关键代码示例。
20.5万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 添加观察者监听特定通知: 在Objective-C中,使用NSNotificationCenter来添加观察者监听通知。关键代码如下:
// 获取通知中心实例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 添加观察者
[center addObserver:self selector:@selector(handleNotification:) name:@"YourNotificationName" object:nil];
// 当收到通知时调用的方法
- (void)handleNotification:(NSNotification *)notification {
    // 处理通知的逻辑
    NSLog(@"Received notification: %@", notification);
}
  1. 移除观察者: 当不再需要监听通知时,要移除观察者,避免内存泄漏。关键代码如下:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 移除观察者
[center removeObserver:self name:@"YourNotificationName" object:nil];

这里YourNotificationName是特定通知的名称,self表示观察者对象,handleNotification:是收到通知时调用的方法。如果在不同的场景下,self可以替换为实际的观察者对象,object参数若指定则只接收特定对象发出的通知,若为nil则接收所有对象发出的该通知。