【问题标题】:How to access a Dictionary passed via NSNotification, using Swift如何使用 Swift 访问通过 NSNotification 传递的字典
【发布时间】: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


    【解决方案1】:

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

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

    // 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 key\n")
      }
    }
    else {
      print("wrong userInfo type")
    }
    

    【讨论】:

    • 总是点击 print("wrong userInfo type") - in swift 2
    • @Async- 它在操场上对我有用。但是,您需要确保所有键和值都是字符串。如果您有不同的类型,则需要在 1st cast 中更改类型
    • 抱歉,是的,它可以工作 - 重置模拟器的内容后,清理并构建它可以工作!
    • 效果很好!谢谢。
    • “UNNotification”类型的值在 4.9.19 中没有成员“userInfo”
    【解决方案2】:

    您应该使用类似[NSObject : AnyObject] 的结构并从NSDictionary yourLet[key] 中检索值

    func keyboardWillShown(notification : NSNotification){
        let tmp : [NSObject : AnyObject] = notification.userInfo!
        let duration : NSNumber = tmp[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
        let scalarDuration : Double = duration.doubleValue
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2011-03-03
      • 2010-12-08
      • 2021-09-21
      相关资源
      最近更新 更多