面试题答案
一键面试- 添加观察者监听特定通知:
在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);
}
- 移除观察者: 当不再需要监听通知时,要移除观察者,避免内存泄漏。关键代码如下:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 移除观察者
[center removeObserver:self name:@"YourNotificationName" object:nil];
这里YourNotificationName
是特定通知的名称,self
表示观察者对象,handleNotification:
是收到通知时调用的方法。如果在不同的场景下,self
可以替换为实际的观察者对象,object
参数若指定则只接收特定对象发出的通知,若为nil
则接收所有对象发出的该通知。