【问题标题】:What is difference between Swift 2.3 and 3 in adding userInfo to NSNotification?将 userInfo 添加到 NSNotification 的 Swift 2.3 和 3 有什么区别?
【发布时间】:2017-01-19 17:39:48
【问题描述】:

我遇到了一个小问题。

假设我有结构

struct AlertNotificationObject {

    let message: String
}

我在 Swift 2.3 中有一个项目,我使用这个 structure 放入 dictionary,然后放入 NSNotification Observer 中的 userInfo:。我无法让它工作,所以为了调查我的问题,我创建了一些游乐场。

Swift 3.0 版本 - 按预期工作。

请注意,我必须创建 epytClass 才能让它在 Swift 3 操场上工作。

class emptyClass{
    @objc public func testFunction(){
        print ("It should work")
    }
}

//MARK: observer //shouldnt bother us now.
let emptyClassRef = emptyClass()

NotificationCenter.default.addObserver(emptyClassRef, selector: #selector(emptyClass.testowFunction), name: NSNotification.Name(rawValue: "test0"), object: nil)

//MARK: post
let messageObject0 = AlertNotificationObject(message: "Test1")
let messageDict0 = [1: messageObject0]

let test0 = NSNotification.init(name: NSNotification.Name(rawValue: "test0"), object: nil, userInfo: messageDict0)
NotificationCenter.default.post(test0 as Notification)

应用内 Swift 2.3 版本 - 除了明显的语法更改外,我无法让它正常工作 - 我卡在了通知发布中。

    let messageObject0 = AlertNotificationObject(message: "test")
    let messageDict = [1: messageObject0]
    let showAlertWithBlur = NSNotification.init(name: "ShowAlertBlur", object: nil, userInfo: messageDict)
    NSNotificationCenter.defaultCenter().postNotification(showAlertWithBlur)

我遇到了一个错误...我想了解这里出了什么问题,最重要的是要知道 为什么它在 Swift 3 中有效。欢迎提出任何建议。

.

【问题讨论】:

    标签: dictionary swift3 structure swift-playground swift2.3


    【解决方案1】:

    在 Swift 3 中,Notification 实际上是一个结构,更新后可以很好地与 swift 配合使用,用户信息字典是 [AnyHashable : Any]。您可以将结构(值类型)放入Any

    如果您直接使用NSNotification(这是您在 Swift 2 中的唯一选择),userInfo 的类型为 NSDictionary,在 Swift 3 中转换为 [AnyHashable: Any],在 Swift 2 中转换为 [NSObject: AnyObject] .

    AnyObject 仅代表类,不能在其中放置结构。

    我的建议 - 在 Swift 2.x 中与 Obj-C 类型交互时不要使用结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多