加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何访问通过NSNotification传递的字典,使用Swift

发布时间:2020-12-14 06:01:45 所属栏目:百科 来源:网络整理
导读:我有代码发送通知(其中serialNumber是一个字符串): var dataDict = DictionaryString,String() dataDict["Identity"] = serialNumber dataDict["Direction"] = "Add" NSNotificationCenter.defaultCenter().postNotificationName("deviceActivity",object:s
我有代码发送通知(其中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代码提取一个对象,在这种情况下一个字典,通过通知,并访问该对象的组件部分(在这种情况下的键和值)?

由于notification.userInfo类型是AnyObject,因此您必须将其下转换为适当的字典类型。

在知道确切类型的字典后,你不需要从它得到的downcast值。但是,在使用它们之前,您可能想要检查值是否实际存在于字典中:

// First try to cast user info to expected type
if let info = notification.userInfo as? Dictionary<String,String> {
  // Check if value present before using it
  if let s = info["Direction"] {
    print(s)
  }
  else {
    print("no value for keyn")
  }
}
else {
  print("wrong userInfo type")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读