mcf*_*oft 22 notifications ios swift
如何通过通知发送数字和字符串...
let mynumber=1;
let mytext="mytext";
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: ?????????????);
Run Code Online (Sandbox Code Playgroud)
并在接收器中接收值?
func refreshList(notification: NSNotification){
let receivednumber=??????????
let receivedString=?????????
}
Run Code Online (Sandbox Code Playgroud)
Pfi*_*itz 31
您可以将它们包装在一个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"]
}
Run Code Online (Sandbox Code Playgroud)
Leo*_*bus 24
Xcode 8.3.1•Swift 3.1
extension Notification.Name {
static let refresh = Notification.Name("refresh")
}
Run Code Online (Sandbox Code Playgroud)
let object: [String: Any] = ["id": 1, "email": "abc@def.com"]
NotificationCenter.default.post(name: .refresh, object: object)
Run Code Online (Sandbox Code Playgroud)
NotificationCenter.default.addObserver(self, selector: #selector(refreshList), name: .refresh, object: nil)
// Swift 4 or later note: add @objc to the selector `@objc func ...`
// don't forget vvv add an underscore before the view controller method parameter
func refreshList(_ notification: Notification) {
if let object = notification.object as? [String: Any] {
if let id = object["id"] as? Int {
print(id)
}
if let email = object["email"] as? String {
print(email)
}
}
}
Run Code Online (Sandbox Code Playgroud)
Eag*_*gic 14
您可以使用以下userInfo属性Notification:
NotificationCenter.default.post(name: Notification.Name("refresh"),
object: nil,
userInfo: ["number":yourNumber, "string":yourString])
Run Code Online (Sandbox Code Playgroud)
并检索:
func refreshList(notification: Notification){
let receivednumber = notification.userInfo?["number"] as? Int ?? 0
let receivedString = notification.userInfo?["string"] as? String ?? ""
}
Run Code Online (Sandbox Code Playgroud)
实际上有很多方法可以做到这一点。其中之一是传递一组对象,例如:
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
}
Run Code Online (Sandbox Code Playgroud)