Swift 2到Swift 3 NSNotification / Notification
发布时间:2020-12-14 04:44:20 所属栏目:百科 来源:网络整理
导读:在 Swift 3.0中使用El Capitan编码下的XCode 8 beta 6 试图将项目中的这些行从Swift 2.0转换为Swift 3.0 let userInfo = ["peer": peerID,"state": state.toRaw()]NSNotificationCenter.defaultCenter.postNotificationName("Blah",object: nil,userInfo: us
在
Swift 3.0中使用El Capitan编码下的XCode 8 beta 6
试图将项目中的这些行从Swift 2.0转换为Swift 3.0 let userInfo = ["peer": peerID,"state": state.toRaw()] NSNotificationCenter.defaultCenter.postNotificationName("Blah",object: nil,userInfo: userInfo) 所以我设法凑齐了这个…… public class MyClass { static let myNotification = Notification.Name("Blah") } let userInfo = ["peerID":peerID,"state":state.rawValue] as [String : Any] NotificationCenter.default.post(name: MyClass.myNotification,object: userInfo) 它在我运行它时编译并发送通知并使用此行设置一个监听器,但没有userInfo我可以解码? let notificationName = Notification.Name("Blah") NotificationCenter.default.addObserver(self,selector: #selector(peerChangedStateWithNotification),name: notificationName,object: nil) 此代码打印“nil”,因为没有userInfo … func peerChangedStateWithNotification(notification:NSNotification) { print("(notification.userInfo)") } 解决方法
正如@vadian所说,NotificationCenter有一个
post(name:object:userInfo :)可以使用的方法. 这是一个独立的例子,它也演示了如何 class MyClass: NSObject { static let myNotification = Notification.Name("Blah") override init() { super.init() // Add observer: NotificationCenter.default.addObserver(self,selector: #selector(notificationCallback),name: MyClass.myNotification,object: nil) // Post notification: let userInfo = ["foo": 1,"bar": "baz"] as [String: Any] NotificationCenter.default.post(name: MyClass.myNotification,userInfo: userInfo) } func notificationCallback(notification: Notification) { if let userInfo = notification.userInfo as? [String: Any] { print(userInfo) } } } let obj = MyClass() // ["bar": baz,"foo": 1] 或者,您可以在中提取字典值 func notificationCallback(notification: Notification) { guard let userInfo = notification.userInfo else { return } if let fooValue = userInfo["foo"] as? Int { print("foo =",fooValue) } if let barValue = userInfo["bar"] as? String { print("bar =",barValue) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |