[英]Observers don't get called using NotificationCenter Swift 4.0
I have a two ViewControllers: ViewController
and SecondViewController
. 我有两个ViewController: ViewController
和SecondViewController
。 I added an observer to this two ViewControllers. 我在这两个ViewController中添加了一个观察者。 In ViewController
I also defined an IBAction to post the notification. 在ViewController
我还定义了一个IBAction来发布通知。 I handle the notification via a closure in both ViewControllers. 我通过两个ViewController中的闭包来处理通知。 But only the closure in the ViewController
gets called. 但是只有ViewController
的闭包被调用。 The closure (and even the whole code) in the SecondViewController
does not get called (I checked with debugger). SecondViewController
中的闭包(甚至整个代码)不会被调用(我已通过调试器进行检查)。 The closure only contains a print-statement. 闭包仅包含打印语句。 Here is my Code 这是我的代码
//ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the : \(type(of: self))")
}
}
@IBAction func sendNotification(_ sender: UIButton) {
let nc = NotificationCenter.default
nc.post(name: Notification.Name(rawValue:"MyNotification"), object: nil, userInfo: ["message":"Hello there!", "Date:":Date()])
}
}
The ScondViewController ScondViewController
//SecondViewController
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the: \(type(of: self))")
}
}
}
The closure in ViewController gets called but the closure in SecondViewController does not. ViewController中的闭包被调用,而SecondViewController中的闭包没有被调用。 Maybe the reason is that SecondViewController does not get initialized before I post the notification. 可能是因为我在发布通知之前未初始化SecondViewController。 But how would a solution look like? 但是解决方案会是什么样子? Any help is appreciated. 任何帮助表示赞赏。
If this is one-to-one relationship you can also use the Delegate pattern instead. 如果这是一对一关系,则也可以使用“委托”模式。 Although you are right, the notification observer is not yet called because you do not initialise before the post. 尽管您是正确的,但由于未在发布之前进行初始化,因此尚未调用通知观察程序。 So there shouldn't be a reason for a function to be called in the SecondViewController. 因此,不应在SecondViewController中调用函数。
So if you only need that to update a variable value, you can do that somewhere else in a Variables
class where both ViewControllers have access. 因此,如果只需要更新变量值,则可以在两个ViewController都可以访问的Variables
类中的其他地方进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.