当它们是两个视图控制器时,NSNotificationCenter在applicationDidEnterBackground中调用了两次?

时间:2015-06-30 11:19:15

标签: ios swift nsnotificationcenter

我使用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

但是在我在Storyboard中添加一个新的视图控制器并使用Segue中的任何一个连接它们之后:

storyboard

storyboard

现在当我运行应用程序时,单击两个按钮然后返回主页,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)
}

2 个答案:

答案 0 :(得分:0)

啊,我忘记了viewDidLoad被加载了两次......我解决了:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "com.test.mytest", object: nil)
}

答案 1 :(得分:0)

我遇到过同样的问题。在我的案例中,解决方案是在项目功能选项卡中启用button#submit