【问题标题】:Adding objects to a dictionary将对象添加到字典
【发布时间】:2017-02-09 13:33:53
【问题描述】:

我正在尝试将 2 个对象添加到字典中,然后再将其发送到 Post 类以获取照片供稿。这就是我所拥有的,我正在使用 firebase。

if let postDict = snap.value as? Dictionary<String, AnyObject> {

         for(name, value) in postDict {
             if name == "postedBy" {

                 DataService.ds.REF_USERS.child(value as! String).observeSingleEventOfType(.Value, withBlock: { (friendDictionary) in

                     let userDict = friendDictionary.value as! NSDictionary
                     value.setValue(userDict.objectForKey("username"), forKey: "username")
                     value.setValue(userDict.objectForKey("profileThumbUrl"), forKey: "profileThumbUrl")
                     self.collectionView?.reloadData()

                 })
             }
         }

         let key = snap.key
         let post = Post(postKey: key, dictionary: postDict)
         self.posts.append(post)

问题在于,当我尝试使用 setValue() 将用户名和 profileThumbUrl 添加到 postDict 中的值时,我收到错误消息:“此类与键用户名的键值编码不兼容。”我在其他情况下使用过这种方法,所以我不知道是不是因为我在开始时使用了“if let”,因为我通常不使用它。有什么想法吗?

【问题讨论】:

  • value 的类型是什么?
  • 你试过不使用 if let 吗?
  • 我认为价值是任何对象
  • 是的,这不是 if let 的事情。我还是想不通。

标签: ios swift for-loop dictionary firebase


【解决方案1】:

objectForKey 返回一个可选类型,它不符合 NSDictionary,因此您需要解开可选类型才能使其工作。

例如

for(name, value) in postDict {
         if name == "postedBy" {

             DataService.ds.REF_USERS.child(value as! String).observeSingleEventOfType(.Value, withBlock: { (friendDictionary) in

                 let userDict = friendDictionary.value as! NSDictionary

                 guard let username = userDict.objectForKey("username") else { continue }
                 guard let profileThumbURL = userDict.objectForKey("profileThumbUrl") else { continue }

                 value.setValue(username, forKey: "username")
                 value.setValue(profileThumbUrl, forKey: "profileThumbUrl")
                 self.collectionView?.reloadData()

             })
         }
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2015-01-13
    • 2012-11-21
    • 2015-09-07
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多