How to Pass Multiple Values with a Notification in Swift

how to pass multiple values with a notification in swift

You could wrap them in an NSArray or a NSDictionary or a custom Object.

Eg:

let mynumber=1;
let mytext="mytext";

let myDict = [ "number": mynumber, "text":mytext]

NSNotificationCenter.defaultCenter().postNotificationName("refresh", object:myDict);

func refreshList(notification: NSNotification){
let dict = notification.object as! NSDictionary
let receivednumber = dict["number"]
let receivedString = dict["mytext"]
}

Passing parameters with #selector

If you want to pass an object around classes that are registered to NotificationCenter, you should put that into .userInfo dictionary of notification object that is passed to observer function:

NotificationCenter.default.addObserver(self, selector: #selector(reload), name: Notification(name: "reload"), object: nil)

--

let userInfo = ["item": items[indexPath.row]]
NotificationCenter.default.post(name: "reload", object: nil, userInfo: userInfo)

--

func reload(_ notification: Notification) {
if let target = notification.userInfo?["item"] as? Item {
print(target.name)
print(target.iconName)
}
}

How to pass a string with NSNotificationCenter?

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.

How to notify a change from a class to multiple ViewControllers?

You can use NotificationCenter https://developer.apple.com/documentation/foundation/notificationcenter to broadcast a message. or use KVO. Generally I consider notification center much easier.

simple example:
https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter



Related Topics



Leave a reply



Submit