Swift中的通知在字典中返回UserInfo

时间:2014-09-19 12:05:29

标签: swift notifications ios8 xcode6

我有一个返回字典的通知,就像在objective-c中一样,但我没有得到我期望的结果。

以下是发布通知的方法。它实际上返回了日期选择器的结果(日期)。

@IBAction func dateOfBirthAction(sender: AnyObject) {

    println("Date: \(dateOfBirthPicker.date)")

    var selectedDateDictionary = [dateOfBirthPicker.date, "dateOfBirth"]

    NSNotificationCenter.defaultCenter().postNotificationName("dateOfBirth", object: nil, userInfo: [NSObject():selectedDateDictionary])

}

以下是通知观察员:

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "dateOfBirth:", name: "dateOfBirth", object: nil)

}

func dateOfBirth(notification: NSNotification) {

    println("userInfo: \(notification.userInfo)")

    let returnedDateOfBirth = notification.userInfo!["dateOfBirth"] as NSString
    println("returnedDateOfBirth: \(returnedDateOfBirth)")

    playerInformationDateOfBirthLabel.text  = returnedDateOfBirth
}

我在第let returnedDateOfBirth:String = notification.userInfo["dateOfBirth"]

上收到以下错误
userInfo: Optional([<NSObject: 0x7fb15a44a880>: <_TtCSs23_ContiguousArrayStorage00007FB15A4D4380 0x7fb15a4206a0>(
2014-09-18 12:07:07 +0000,
dateOfBirth
)
])
fatal error: unexpectedly found nil while unwrapping an Optional value

完整解决方案

@IBAction func dateOfBirthAction(sender: AnyObject) {

    var selectedDateDictionary = ["birthDate" : dateOfBirthPicker.date]

    NSNotificationCenter.defaultCenter().postNotificationName("foundABirthDate", object: nil, userInfo:selectedDateDictionary)
}

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "dateOfBirth:", name: "foundABirthDate", object: nil)

}

func dateOfBirth(notification: NSNotification) {

    let playerBirthDate = notification.userInfo!["birthDate"] as NSDate

    var dateFormatter: NSDateFormatter = NSDateFormatter()

    //Specifies a long style, typically with full text, such as “November 23, 1937”.
    dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle

    let dateConvertedToString: String = dateFormatter.stringFromDate(playerBirthDate)

    playerInformationDateOfBirthLabel.text  = dateConvertedToString
}

2 个答案:

答案 0 :(得分:9)

您的userInfo字典错误。

你有:

[NSObject():selectedDateDictionary]

尝试将userInfo设置为userInfo: selectedDateDictionary,如下所示:

NSNotificationCenter.defaultCenter().postNotificationName("dateOfBirth", object: nil, userInfo: selectedDateDictionary)

由于String但您返回returnedDateOfBirth:String

,错误告诉您预计[NSObject():selectedDateDictionary] {{1}}

答案 1 :(得分:2)

试试吧 只有字典可以传递给userInfo

        var pageDict: Dictionary<String,String>! = [
            "dateOfBirth": "11/5/1987date",
        ]
        NSNotificationCenter.defaultCenter().postNotificationName("dateOfBirth", object: nil, userInfo: pageDict)

     NSNotificationCenter.defaultCenter().postNotificationName("dateOfBirth", object: pageDist, userInfo: nil)