微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个通知返回一个字典,很像在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 returnDateOfBirth: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",userInfo:selectedDateDictionary)
}

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addobserver(self,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
}
你的userInfo字典是错误的。

你有:

[NSObject():selectedDateDictionary]

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

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

错误是告诉你,你期望一个String,因为returnedDateOfBirth:String,但你返回[NSObject():selectedDateDictionary]

原文地址:https://www.jb51.cc/swift/320639.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐