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