Swift 中的 NSNotificationCenter addObserver

swiftserver side programmingprogramming更新于 2025/8/8 13:07:17

本文旨在解释 iOS 应用程序如何使用 NSNotificationCenter 发送和接收更改事件。

在 iOS 应用程序中,您可能需要在应用程序的任何位置发送和接收事件。当您需要在应用程序的任何位置接收事件时,使用 NSNotificationCenter 类可能会很有用。在这种情况下,您可以监听事件并做出相应的响应。

Foundation 框架中的 NSNotificationCenter 类提供了一种向已注册的观察者广播通知的机制。它允许对象之间相互通信并响应程序中发生的事件。

如何发布事件?

语法

NotificationCenter.default.post(name: <NSNotification.Name>, object: <Any?>, userInfo: <[AnyHashable : Any]?>)

NotificationCenter 提供了一个 post() 方法来发送事件。要发布事件,您必须传递通知名称作为身份信息。如果您不想发送任何其他信息,可以忽略对象和用户信息。

示例

以下是如何使用 NSNotificationCenter 发布通知的示例 -

import Foundation class User { var userId: String = "" func doLogout() { // write your code to logout the user // you will send an event once the user will be logged out. For example, NotificationCenter.default.post(name: NSNotification.Name("UserLoggedOut"), object: nil, userInfo: ["userId": userId]) } }

如何接收事件?

语法

NotificationCenter.default.addObserver(<observer: Any>, selector: <Selector>, name: <NSNotification.Name?>, object: <Any?>)

NotificationCenter 提供了一个 addObserver() 方法来接收事件。要监听事件,您需要为目标通知名称添加一个观察者。发送一个对象后,您将收到一个对象。

示例

以下是如何使用 NSNotificationCenter 接收通知的示例 -

import Foundation import UIKit class HomeController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(handleLoggedOutNotification), name: NSNotification.Name("UserLoggedOut"), object: nil) } @objc private func handleLoggedOutNotification(_ notification: NSNotification) { print("notification: \(notification)") /* {name = UserLoggedOut; userInfo = { userId = 123; }} */ } }

在此示例中,User 实例使用 NSNotificationCenter 的 post 方法发送"UserLoggedOut"通知。HomeController 类已注册为此通知的观察者,并在收到通知时调用其 handleLoggedOutNotification 方法。

必须注意,通知是异步广播的,这意味着观察者可能不会在通知发送后立即收到通知。

管理您的自定义通知

在实际应用中,您可能需要发送和接收多个具有自定义名称的通知。发送通知后,您必须传递 NSNotificationName 对象来标识该通知。

示例

要注册您自己的自定义通知,我们建议您为 NSNotification.Name 类编写一个扩展,并将所有相关通知添加到其中。例如,

Import Foundation extension NSNotification.Name { static let userLoggedIn = NSNotification.Name("userLoggedIn") static let userLoggedOut = NSNotification.Name("userLoggedOut") static let userProfilePhotoChanged = NSNotification.Name("userProfilePhotoChanged") }

我们正在扩展 NSNotificationName 并添加不同的通知名称。

现在,在发送和接收通知时提供名称将变得非常简单,如下所示 -

import Foundation func send() { NotificationCenter.default.post(name: .userLoggedOut, object: nil, userInfo: ["userId": "123"]) } func receive() { NotificationCenter.default.addObserver(self, selector: #selector(handleLoggedOutNotification), name: .userLoggedOut, object: nil) } @objc private func handleLoggedOutNotification(_ notification: NSNotification) { print("notification: \(notification)") }

NSNotification Center 有三种重载方法来发布通知 -

  • NotificationCenter.default.post(notification:) - 如果您只需要发布一个没有任何上下文的通知,请使用此方法。

  • NotificationCenter.default.post(name:object:) - 如果您需要发布通知并关心发布者,请使用此方法。通知发送者是通知的对象,发布通知的对象是通知本身。

  • NotificationCenter.default.post(name:object:userInfo:) - 此方法是功能最齐全的方法。您需要指定通知名称、对象(同样是发送者)以及一个 userInfo 字典。您可以使用此字典向观察者提供其他数据。在我们的示例中,我们可以提供刚刚添加到应用中的图片。

结论

使用 NotificationCenter 类发送和接收事件时,请记住它们会在整个应用中广播消息。您必须非常谨慎地发送和接收事件,并且仅在需要时才发送。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部