Nil在通过NSNotifications传递信息时?

时间:2016-07-28 20:15:28

标签: ios swift nsnotificationcenter

我有一个控制在屏幕上拖动UIButton的类。我想要在touchesEnded上捕捉按钮的标签/最终位置。

我已经进入了DragImageClass:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let dict =  ["position":String(self.center),"tag": String(self.tag)]

    NSNotificationCenter.defaultCenter().postNotificationName("buttonDropped", object: nil, userInfo: dict)

    print(dict["position"]) // Does get printed
    print("Should have sent") // Does get called
}

然后在我的主视图中,我需要获得的信息:

我的观察员:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(testController.touchesStopped(_:)), name: "buttonDropped", object: nil)

我的功能:

func touchesStopped(notif : AnyObject) {
    if let dict = notif.object as? NSDictionary { //Some error with this data type I guess?
        let position = dict["position"]
        let tag = dict["tag"]
        print(position)  // doesn't get printed
        print(tag) // doesn't get printed
    }
}

为什么我从这些价值观中恢复过来的任何想法?当我试图强行打开它时,它只是给了我一个&#34; Thread bad instruction&#34;的事情。

2 个答案:

答案 0 :(得分:2)

Looking at the documentation, NSNotification.userInfo is imported into Swift as [NSObject: AnyObject]?. Try this instead:

guard let notif = notif as? NSNotification,
   let dict = notif.userInfo as? [NSObject: AnyObject] else {
    return
}

let position = dict["position"]
let tag = dict["tag"]

print(position)  // doesn't get printed
print(tag) // doesn't get printed

答案 1 :(得分:2)

正如您在调用中看到的那样,该对象为nil,因为您将字典作为userInfo传递(这是正确的方法):

NSNotificationCenter.defaultCenter().postNotificationName("buttonDropped", object: nil, userInfo: dict)

因此,为了获取该字典,请不要使用通知的object属性,请使用userInfo属性:

func touchesStopped(notif: NSNotification) {
    if let dict = notif.userInfo {
        let position = dict["position"]
        let tag = dict["tag"]
        print(position)
        print(tag)
    }
}

旁注:将一个点转换为一个字符串并返回一个点会很痛苦,你应该使用NSValue来代替:

let dict: [String:AnyObject] = [
    "position": NSValue(CGPoint: self.center),
    "tag": self.tag
]
let position = (dict["position"] as? NSValue)?.CGPointValue()
let tag = dict["tag"] as? Int