【发布时间】:2016-04-20 02:23:49
【问题描述】:
我目前在 NSTimer 中多次使用 postNotification,但观察者只收到一次。
在不添加多个观察者的情况下多次接收相同通知的方法是什么?
我的计时器是这样创建的:
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(update) , userInfo: nil, repeats: true)
而里面的更新方法是:
let testNotification: NSNotification = NSNotification(name: "testNotification", object: self, userInfo: nil)
NSNotificationCenter.defaultCenter().postNotification(testNotification)
这就是我在其中一个视图控制器中注册观察者的方式:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(testNot), name: "testNotification", object: nil)
updateView()
}
我像往常一样在视图控制器中添加观察者。
我可以确认计时器工作正常,因为 update() 是定期调用的,并且观察者确实第一次收到通知,但它没有再次发生。
如果您需要查看更多代码,请告诉我。
【问题讨论】:
-
您需要向我们展示创建计时器的代码和发布通知的代码。
-
以及注册通知的代码。
-
你把取消注册视图控制器的方法放在哪里了?也许在 viewDidDisappear 或 testNot 中
-
我没有。我尝试在 testNot() 中删除并重新添加观察者,但这也不起作用。
-
这一切发生在一个类还是两个不同的类中?
标签: swift nsnotification