当我使用以下代码时:
override func viewDidLoad() {
nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(self.receivedNotification), name:MyNotification, object: nil)
}
func receivedNotification() -> void {
NSLog("notification received")
}
receivedNotification
永远不会被称为
但是当我使用以下关闭方式时
nc.default.addObserver(forName:MyNotification, object:nil, queue:nil) {
notification in
NSLog("notification received")
}
成功调用 NSLog("...")
。
有人可以解释一下这里发生了什么
答案 0 :(得分:0)
接收(获取)通知
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
func methodOfReceivedNotification(notification: Notification){
//Take Action on Notification
}
发送(发布)通知:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
停止收听通知
NotificationCenter.default.removeObserver(self, name: "NotificationIdentifier", object: nil);
答案 1 :(得分:0)
请尝试以下代码。它成功调用了nslog。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(self.receivedNotification), name:NSNotification.Name(rawValue: "MyNotification"), object: nil)
}
func receivedNotification() {
NSLog("notification received")
}
//发布通知
let nc = NotificationCenter.default
nc.post(name: NSNotification.Name(rawValue: "MyNotification"), object: nil)
答案 2 :(得分:0)
您可以使用此方法获取名为
的本地通知 override func viewDidLoad() {
nc = NotificationCenter.default
nc.addObserver(forName:MyNotification, object:nil, queue:nil, using:receivedNotification)
}
func receivedNotification() -> void {
NSLog("notification received")
}
并发布通知
NotificationCenter.default.post(name: Notification.Name("MyNotification"), object: nil)