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

Pau*_* S. 22 notifications swift xcode6 ios8

我有一个返回字典的通知,就像在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])

}
Run Code Online (Sandbox Code Playgroud)

这是通知观察员:

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

我在线路上收到以下错误 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
Run Code Online (Sandbox Code Playgroud)

完整的解决方案

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

Aus*_*son 9

你的userInfo字典错了.

你有:

[NSObject():selectedDateDictionary]
Run Code Online (Sandbox Code Playgroud)

尝试设置userInfouserInfo: selectedDateDictionary这样:

NSNotificationCenter.defaultCenter().postNotificationName("dateOfBirth", object: nil, userInfo: selectedDateDictionary)
Run Code Online (Sandbox Code Playgroud)

错误告诉你,你正在期待String因为returnedDateOfBirth:String但是你回来了[NSObject():selectedDateDictionary]