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
Uitableview and Uiview with Keyboardwillshow
Iad Is Shutting Down. Should I Remove the Iad Framework from All My Applications
How to Set Cg_Context_Show_Backtrace Environmental Variable
Uitableview Load More When Scrolling to Bottom Like Facebook Application
Behaviour for Significant Change Location API When Terminated/Suspended
How to Create a Delay in Swift
iOS 8 Rotation Methods Deprecation - Backwards Compatibility
How to Get the Console Logs from the iOS Simulator
Uitextview That Expands to Text Using Auto Layout
Get Size of a View in React Native
Presenting a Uialertcontroller Properly on an iPad Using iOS 8
iOS Multiple Columns in Uitableview
How to Add Unique Constraints for Some Fields in Core Data
Xcode 6.1 Missing Required Architecture X86_64 in File
Google Plus API for Posting on Wall Like Facebook