【问题标题】:Issues with NSNotificationCenter in @IBAction function@IBAction 函数中的 NSNotificationCenter 问题
【发布时间】:2015-11-18 01:55:17
【问题描述】:

我正在开发一个需要我的主视图控制器从其子视图控制器接收通知的应用程序。为此,我在父控制器的viewDidLoad() 方法中设置了观察者,并尝试在按下位于子视图控制器中的按钮时调用postNotificationName() 函数。

postNotificationName() 调用位于@IBAction func buttonPressed(){ } 函数中时,观察者永远不会收到通知。但是,当从同一个视图控制器中的不同函数调用相同的代码时,它会起作用。

我认为这可能是线程问题,但针对该问题尝试了许多解决方案均未成功。不过,我对线程不是很熟悉,所以也许我仍然错过了它。有谁知道问题可能是什么?

感谢您的帮助!

视图控制器

class GameController: UIViewController {

override func viewDidLoad() {

    super.init()


    NSNotificationCenter.defaultCenter().addObserver(self, selector: "attemptHumanMove:", name: Constants.NSNotificationKey.tilePressed, object: nil)

}


func attemptHumanMove(notification: NSNotification) {
    print("test")
}

ChildViewController

@IBAction func tileTouched(sender: AnyObject) {
    NSNotificationCenter.defaultCenter().postNotificationName(Constants.NSNotificationKey.tilePressed, object: nil, userInfo: ["a": 0])
}

【问题讨论】:

  • 你确定你的 IBAction 方法被调用了吗?
  • 是的,已经用断点确认
  • 发布您的完整代码,从您开始收听通知的位置到您发布通知的位置。
  • 我想我发布了代码的所有必要部分。希望这可以帮助。真的没什么。
  • 我能想到的唯一另一件事是您的 addObserver 没有及时注册,或者其中一个正在被释放。除了这些建议,我不确定。

标签: xcode swift nsnotificationcenter ibaction nsnotification


【解决方案1】:

用您提到的流程进行实验,以下代码确实收到了来自子视图控制器的通知消息。

父视图控制器

class ViewController: UIViewController {

    @IBOutlet weak var notificationMsgLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        notificationMsgLabel.text = "Waiting for notification..."
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "attemptHumanMove:", name: "tilePressed", object: nil)
    }

    func attemptHumanMove(notification: NSNotification) {
        print("Notification message received!")
        notificationMsgLabel.text = "Notification received!!!"
    }
}

ChildViewController

class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func sendNotification() {
        print("Sending notification message!!!")
        NSNotificationCenter.defaultCenter().postNotificationName("tilePressed", object: nil, userInfo: ["a": 0])
    }
}

您可以在此处找到故事板的屏幕截图: Storyboard Snapshot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多