#ios
NSNotificationCenter是 Objective-C 中的一个类,用于在应用内广播信息。它允许对象相互通信,而无需直接引用。下面简要介绍一下它的工作原理:
您可以使用以下方式发布通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:nil userInfo:@{@"key": @"value"}];
要接收通知,请注册一个观察员:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:@"MyNotification"
object:nil];
您实现一个方法来处理通知:
- (void)handleNotification:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
// Handle the notification
}
当不再需要观察者时,不要忘记将其删除,以避免内存泄漏:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"MyNotification"
object:nil];