Swift 2到Swift 3 NSNotification/Notification

use*_*232 5 notifications swift

使用XCode 8 beta 6El Capitan编码Swift 3.0

试图将项目中的这些行转换Swift 2.0Swift 3.0

let userInfo = ["peer": peerID, "state": state.toRaw()]
NSNotificationCenter.defaultCenter.postNotificationName("Blah", object: nil, userInfo: userInfo)
Run Code Online (Sandbox Code Playgroud)

所以我设法凑齐了这个......

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)
Run Code Online (Sandbox Code Playgroud)

它在我运行它时编译并发送通知并使用此行设置一个监听器,但没有userInfo我可以解码?

 let notificationName = Notification.Name("Blah")
    NotificationCenter.default.addObserver(self, selector: #selector(peerChangedStateWithNotification), name: notificationName, object: nil)
Run Code Online (Sandbox Code Playgroud)

此代码打印"nil",因为没有userInfo ...

func peerChangedStateWithNotification(notification:NSNotification) {
    print("\(notification.userInfo)")
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 7

正如@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,
                                        object: nil,
                                        userInfo: userInfo)
    }

    func notificationCallback(notification: Notification) {
        if let userInfo = notification.userInfo as? [String: Any] {
            print(userInfo)
        }
    }
}

let obj = MyClass()
// ["bar": baz, "foo": 1]
Run Code Online (Sandbox Code Playgroud)

或者,您可以像这样在回调中提取字典值(也可以从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)
        }
    }
Run Code Online (Sandbox Code Playgroud)