obsidian/笔记文件/2.笔记/NSNotificationCenter.md
2025-03-26 00:02:56 +08:00

1.2 KiB

#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];