加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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 :)可以使用的方法.

这是一个独立的例子,它也演示了如何
将userInfo转换回预期类型的??字典
(摘自https://forums.developer.apple.com/thread/61578):

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]

或者,您可以在中提取字典值
这样的回调(也来自Apple Developer Forum主题):

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)
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读