如何快速传递多个值与通知
如何通过通知发送一个数字和一个string…
let mynumber=1; let mytext="mytext"; NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: ?????????????);
并在接收器中接收值?
func refreshList(notification: NSNotification){ let receivednumber=?????????? let receivedString=????????? }
你可以把它们包装在一个NSArray
或一个NSDictionary
或一个自定义对象中。
例如:
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"] }
Xcode 8.3.1•Swift 3.1
extension Notification.Name { static let refresh = Notification.Name("refresh") }
let myDict: [String: Any] = ["myInt": 1, "myText": "text"] NotificationCenter.default.post(name: .refresh, object: myDict)
NotificationCenter.default.addObserver(self, selector: #selector(refreshList), name: .refresh, object: nil) // don't forget vvv add an underscore before the view controller method parameter func refreshList(_ notification: Notification) { if let myDict = notification.object as? [String: Any] { if let myInt = myDict["myInt"] as? Int { print(myInt) } if let myText = myDict["myText"] as? String { print(myText) } } }
使用userInfo
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: ["number":yourNumber, "string":yourString]
并检索:
func refreshList(notification: NSNotification){ let userInfo = notification.userInfo as Dictionary let receivednumber = userInfo["number"] let receivedString = userInfo["string"] }
我不是很快(未经testing),但你明白了。
其实有很多方法可以做到这一点。 其中之一是传递一组对象,如:
let arrayObject : [AnyObject] = [mynumber,mytext] NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: arrayObject) func refreshList(notification: NSNotification){ let arrayObject = notification.object as! [AnyObject] let receivednumber = arrayObject[0] as! Int let receivedString = arrayObject[1] as! String }
Swift 4.0,我通过单键:值,你可以添加多个键和值。
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "updateLocation"), object: ["location":"India"])
添加观察者和方法定义
NotificationCenter.default.addObserver(self, selector: #selector(getDataUpdate), name: NSNotification.Name(rawValue: "updateLocation"), object: nil) @objc func getDataUpdate(notification: Notification) { guard let object = notification.object as? [String:Any] else { return } let location = object["location"] as? String self.btnCityName.setTitle(location, for: .normal) print(notification.description) print(notification.object ?? "") print(notification.userInfo ?? "") }