3

Class1:

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

Class2:

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

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

I have tried to pass the string in the object parameter (in Class1) but I am not sure what I have to do in Class2 to receive it.

Thank you

MeV
  • 3,761
  • 11
  • 45
  • 78

3 Answers3

4
// 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"]
gowthaman-mallow
  • 692
  • 1
  • 6
  • 10
2

A notification has a userInfo dictionary where you can pass anything you like. Set this up when you post the notification by calling postNotificationName:object:userInfo:. Then receive it through the notification parameter to the handler:

func handle_notification(n:NSNotification) {
    let d = n.userInfo // you take it from here...
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Actual example code here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk1ch10p428foundationClasses/bk1ch10p428foundationClasses/AppDelegate.swift – matt Nov 05 '15 at 17:43
  • Thank you matt. Really helpful. – MeV Nov 05 '15 at 18:34
2

Pass string as in the userInfo data of the notification when posting the notification.

To get the string you need to setup your notification observer so the notification is passed to the selector. To do this, change the selector name to "handle_notification:". Note the addition of the colon. Now add an NSNotification parameter to your handle_notification method.

Now you can get the string from the userInfo of the NSNotification parameter.

BTW - standard naming conventions state that methods names should use camel case, not underscores. So the method should be handleNotification.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • No. Do _not_ pass string as the object. This is wrong. The object should be the sender of the notification, or nil. Secondary data should be in the `userInfo`; that is what it is for. – matt Nov 05 '15 at 17:46
  • @matt Yeah, that is a better solution but using `object` would work. It's just not proper. Answer updated. – rmaddy Nov 05 '15 at 17:49
  • Thanks for the details matt. I understood what is the problem and will use userInfo but I have find out that the main problem was the missing colon when calling the selector – MeV Nov 05 '15 at 18:35