当 NSNotificationCenter 是两个视图控制器时,他们在 applicationDidEnterBackground 中调用了两次?
NSNotificationCenter called twice in applicationDidEnterBackground when their is two view controller?
我正在使用 NSNotificationCenter.defaultCenter().postNotificationName
函数和 applicationDidEnterBackground
函数。所以首先我将这些添加到 AppDelegate.swift
:
func applicationDidEnterBackground(application: UIApplication) {
println("applicationDidEnterBackground")
NSNotificationCenter.defaultCenter().postNotificationName("com.test.mytest", object: self)
}
然后我将这些添加到 ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "myTestFunc", name: "com.test.mytest", object: nil)
}
func myTestFunc () {
println("CALLED")
}
到目前为止,一切正常,当我进入后台时,控制台打印出正确的内容:
applicationDidEnterBackground
CALLED
但是在我在情节提要中添加一个新的视图控制器并使用任何 Segue 连接它们之后:
现在当我 运行 应用程序时,在我单击两个按钮然后返回主页后,applicationDidEnterBackground 仍然调用一次但 NSNotificationCenter 被调用两次:
applicationDidEnterBackground
CALLED
CALLED
那么我该如何解决这个奇怪的问题呢?
编辑
我也试过了,结果还是一样:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().removeObserver(self, name: "com.test.mytest", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "myTestFunc", name: "com.test.mytest", object: nil)
}
啊,我忘了viewDidLoad加载了两次...我解决了:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "com.test.mytest", object: nil)
}
我遇到过同样的问题。在我的案例中,解决方案是在项目功能选项卡中启用 Background Modes
。
我正在使用 NSNotificationCenter.defaultCenter().postNotificationName
函数和 applicationDidEnterBackground
函数。所以首先我将这些添加到 AppDelegate.swift
:
func applicationDidEnterBackground(application: UIApplication) {
println("applicationDidEnterBackground")
NSNotificationCenter.defaultCenter().postNotificationName("com.test.mytest", object: self)
}
然后我将这些添加到 ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "myTestFunc", name: "com.test.mytest", object: nil)
}
func myTestFunc () {
println("CALLED")
}
到目前为止,一切正常,当我进入后台时,控制台打印出正确的内容:
applicationDidEnterBackground
CALLED
但是在我在情节提要中添加一个新的视图控制器并使用任何 Segue 连接它们之后:
现在当我 运行 应用程序时,在我单击两个按钮然后返回主页后,applicationDidEnterBackground 仍然调用一次但 NSNotificationCenter 被调用两次:
applicationDidEnterBackground
CALLED
CALLED
那么我该如何解决这个奇怪的问题呢?
编辑
我也试过了,结果还是一样:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().removeObserver(self, name: "com.test.mytest", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "myTestFunc", name: "com.test.mytest", object: nil)
}
啊,我忘了viewDidLoad加载了两次...我解决了:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "com.test.mytest", object: nil)
}
我遇到过同样的问题。在我的案例中,解决方案是在项目功能选项卡中启用 Background Modes
。