如何使用 NSNotificationCenter 传递字符串?

How to pass a string with NSNotificationCenter?

第 1 类:

var string = "hello"
NSNotificationCenter.defaultCenter().postNotificationName("notificationA", object: nil)

第 2 类:

NSNotificationCenter.defaultCenter().addObserver(self,selector: "handle_notification",name: "notificationA",object: nil)

func handle_notification(){
  //I would like to get the string here
}

我试图在对象参数中传递字符串(在 Class1 中),但我不确定在 Class2 中我必须做什么才能接收它。

谢谢

通知有一个 userInfo 字典,您可以在其中传递您喜欢的任何内容。当您通过调用 postNotificationName:object:userInfo: 通知 post 时设置此项。然后通过通知参数接收到handler:

func handle_notification(n:NSNotification) {
    let d = n.userInfo // you take it from here...
}

在发布通知时传递 string 作为通知的 userInfo 数据。

要获取字符串,您需要设置通知观察器,以便将通知传递给选择器。为此,将选择器名称更改为 "handle_notification:"。注意冒号的添加。现在向您的 handle_notification 方法添加一个 NSNotification 参数。

现在您可以从 NSNotification 参数的 userInfo 中获取字符串。

顺便说一句 - 标准命名约定规定方法名称应使用驼峰式大小写,而不是下划线。所以方法应该是handleNotification.

// sender notification

  let dic = ["myText":"YourText"]  
NSNotificationCenter.defaultCenter().postNotificationName("ApplicationEnterForeground",object: nil, userInfo: dic)

// receiver notification

  NSNotificationCenter.defaultCenter().addObserver(self, selector: "myMethod:", name: "ApplicationEnterForeground", object: nil)

func myMethod(notification: NSNotification) {

labelNotificationText.text = notification.userInfo!["myText"]