How do you store a dictionary on Parse using swift

2019-09-02 01:17发布

问题:

I am very new to swift and I don't know Obj C at all so many of the resources are hard to understand. Basically I'm trying to populate the dictionary with PFUsers from my query and then set PFUser["friends"] to this dictionary. Simply put I want a friends list in my PFUser class, where each friend is a PFUser and a string. Thanks!

        var user = PFUser()
        var friendsPFUser:[PFUser] = []
        var friendListDict: [PFUser:String] = Dictionary()

        var query = PFUser.query()
        query!.findObjectsInBackgroundWithBlock {
            (users: [AnyObject]?, error: NSError?) -> Void in

            if error == nil {
                // The find succeeded.
                println("Successfully retrieved \(users!.count) users.")
                // Do something with the found objects
                if let users = users as? [PFUser] {
                    friendsPFUser = users
                    for user in friendsPFUser{
                        friendListDict[user] = "confirmed"
                    }
                    user["friends"] = friendListDict //this line breaks things
                    user.saveInBackground()
                }
            } else {
                // Log details of the failure
                println("Error: \(error!) \(error!.userInfo!)")
            }
        }

To be clear, this code compiles but when I add

user["friends"] = friendListDict

my app crashes.

回答1:

For those who might have this issues with. "NSInternalInconsistencyException" with reason "PFObject contains container item that isn't cached." Adding Objects to a user (such as arrays or dictionaries) for security reasons on Parse, the user for such field that will be modified must be the current user. Try signing up and using addObject inside the block and don't forget do save it! It helped for a similar problem I had.