ios - 将 NSDictionary 存储在永久内存中 NSUserDefaults 抛出 setValue :forUndefinedKey

标签 ios xcode swift dictionary nsuserdefaults

我正在尝试优化我的应用程序,因为加载时间似乎非常慢。现在我正在制作新闻源。我要做的第一件事是保存 [followingId : followPFUser] 的字典,其中包含 id 和与该 userId 对应的 PFUser。由于某些原因,当我运行该函数时,它给了我这个错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_TtGCSs29_NativeDictionaryStorageOwnerSSCSo6PFUser_ 0x13f5a5440> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key 2NWK7vm8cK.'

我认为字典有问题,但我无法弄清楚。这是我的代码:

func updateFollowing(){
        if self.followedUsers.count > 0{
            print("found some data")
            let getPeopleFollowedByUser = PFQuery(className: "Followers")
            getPeopleFollowedByUser.whereKey("following", equalTo: (PFUser.currentUser()?.objectId!)!)
            getPeopleFollowedByUser.findObjectsInBackgroundWithBlock({ (followingObjects, error) -> Void in
                if error == nil {
                    for followingObject in followingObjects! {

                        let followed = followingObject.objectForKey("followed") as! String
                        var duplicate : Bool = false
                        for (userId, user) in self.followedUsers {
                            if followed == userId as! String {
                                duplicate = true
                            }
                        }
                        if (!duplicate){
                        let followedInfoQuery = PFUser.query()!
                        followedInfoQuery.getFirstObjectInBackgroundWithBlock({ (user, error ) -> Void in
                            if error == nil {
                                if let user = user as? PFUser{
                                self.followedUsers.setValue(user, forKey: followed)
                                }
                            }else{
                                print(error)
                            }
                        NSUserDefaults.standardUserDefaults().setObject(self.followedUsers, forKey: "followedUsers")
                        })
                        }
                    }
                }else{
                    print(error)
                }
            })

        }else{
            print("No data saved")
            var users : NSDictionary = [String : PFUser]()
            if let permanentList = NSUserDefaults.standardUserDefaults().objectForKey("followedUsers") as? [String : PFUser] {
                users = permanentList
            }
            if users.count > 0 {
                for (userId, user) in users {
                    self.followedUsers.setValue(user, forKey: userId as! String)
                }
            }
            let getPeopleFollowedByUser = PFQuery(className: "Followers")
            getPeopleFollowedByUser.whereKey("following", equalTo: (PFUser.currentUser()?.objectId!)!)

            do{
                let followingObjects = try getPeopleFollowedByUser.findObjects()
                for followingObject in followingObjects {
                    let followed = followingObject.objectForKey("followed") as! String
                    let followedInfoQuery = PFUser.query()!

                    do{
                        let user = try followedInfoQuery.getObjectWithId(followed) as! PFUser
                        print(user)
                        self.followedUsers.setValue(user, forKey: followed)
                    }catch let err{
                        print(err)
                    }
                }
                NSUserDefaults.standardUserDefaults().setObject(self.followedUsers, forKey: "followedUsers")
            }catch let err{
                print(err)
            }


        }
    }

如果您发现任何可能导致问题的内容,请告诉我! 谢谢!

编辑:我跟踪了调试错误,显然它在这一行崩溃了:

self.followedUsers.setValue(user, forKey: followed)

我尝试将其更改为 self.followedUser[followed] = userself.followedUsers.setObject(user, forKey: follow) 但它不会构建这两者中的任何一个。

最佳答案

首先(根据@JAL)您错误地设置了字典self.followedUsers。您应该执行 self.followedUsers[followed] = userself.followedUsers.setObject(user, forKey: followed)

其次,NSUserDefaults只能存储某些类型的数据。来自 documentation :

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

因此,您的错误是由于您尝试保存一个字典,其中包含不属于这些类之一的值的Followers

关于ios - 将 NSDictionary 存储在永久内存中 NSUserDefaults 抛出 setValue :forUndefinedKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35877419/

相关文章:

ios - 如何找出静态 TableView 单元格属于哪个部分?

ios - 与主线程相比,何时应异步执行任务?

ios - 如何借助 UISlider 快速更改 ios 音量

ios - UIStackView,2 个标签 : Change Axis based on size

ios - 如何在 Xcode(iOS 应用程序)中使用测试

ios - 如何像whatsapp一样根据文本长度增加UITextview高度

ios - Swift Storyboard ListView 不起作用?

SwiftUI 删除 NavigationView 列表顶部的间距

ios - 如何为所有 session 缓存 UIWebView 页面

ios - 如果所有文本字段都完整,则在 swift 4 中正确显示消息?