在iOS开发中,使用NotificationCenter.default发送通知并传递userInfo是一个常见的需求。下面我将详细说明如何实现这一功能,并给出具体的代码示例。
1. 获取全局的通知中心实例
首先,你需要获取全局的通知中心实例。在Swift 3.0及更高版本中,可以通过NotificationCenter.default来获取。
let notificationCenter = NotificationCenter.default
2. 注册观察者
在需要接收通知的地方注册观察者。你可以通过addObserver方法来注册观察者,并指定通知名称、对象和队列。当有通知触发时,会调用指定的回调函数进行处理。
notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name("MyNotification"), object: nil)
3. 发送通知
使用post方法发送通知,指定通知名称、对象和用户信息。用户信息是一个字典,可以包含任何你需要传递的数据。
let userInfo: [String: Any] = ["name": "张三", "age": 25]
notificationCenter.post(name: NSNotification.Name("MyNotification"), object: self, userInfo: userInfo)
4. 处理通知
在回调函数中处理接收到的通知。你可以通过notification.userInfo来获取传递的数据。
@objc func handleNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
if let name = userInfo["name"] as? String, let age = userInfo["age"] as? Int {
print("接收到的通知内容:name = \(name), age = \(age)")
}
}
}
5. 移除观察者
当观察者不再需要接收通知时,应该移除观察者以避免内存泄漏。通常在deinit方法中移除观察者。
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("MyNotification"), object: nil)
}
完整示例代码
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 注册观察者
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name ("MyNotification"), object: nil)
}
@objc func handleNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
if let name = userInfo["name"] as? String, let age = userInfo["age"] as? Int {
print("接收到的通知内容:name = \(name), age = \(age)")
}
}
}
@IBAction func sendNotificationButtonTapped(_ sender: UIButton) {
// 发送通知
let userInfo: [String: Any] = ["name": "张三", "age": 25]
NotificationCenter.default.post (name: NSNotification.Name ("MyNotification"), object: self, userInfo: userInfo)
}
deinit {
// 移除观察者
NotificationCenter.default.removeObserver(self, name: NSNotification.Name ("MyNotification"), object: nil)
}
}
在这个示例中,当用户点击按钮时,会发送一个包含用户信息的通知。注册了该通知的观察者会在接收到通知后打印出用户信息。这样就实现了通过NotificationCenter发送通知并传递userInfo的功能。