【发布时间】:2014-07-22 16:09:52
【问题描述】:
我有发送通知的代码(其中 serialNumber 是一个字符串):
var dataDict = Dictionary<String, String>()
dataDict["Identity"] = serialNumber
dataDict["Direction"] = "Add"
NSNotificationCenter.defaultCenter().postNotificationName("deviceActivity", object:self, userInfo:dataDict)
以及接收此通知的代码:
func deviceActivity(notification: NSNotification) {
// This method is invoked when the notification is sent
// The problem is in how to access the Dictionary and pull out the entries
}
我尝试了多种代码来完成此操作,但均未成功:
let dict = notification.userInfo
let dict: Dictionary<String, String> = notification.userInfo
let dict: Dictionary = notification.userInfo as Dictionary
虽然我的一些尝试使编译器满意,但在尝试访问提取为字典的内容时,没有一个产生实际的字符串:
let sn : String = dict["Identity"]!
let sn : String = dict.valueForKey("Identity") as String
let sn : String = dict.valueForKey("Identity")
所以问题是这样的:如何编写 Swift 代码来提取通过通知传递的对象(在本例中为字典)并访问该对象的组成部分(在本例中为键和值) ?
【问题讨论】:
标签: dictionary notifications swift