NSUserdefault 不适用于 PFObject

NSUserdefault not working with PFObject

我正在制作一个聊天应用程序,JSQMessagesVC。我想要实现的是,当用户点击聊天按钮时,它会自动显示最新的聊天对话。我认为 NSUserDefault 是实现这一目标的好方法。

在 MessageVC 中,我编写了当用户来自特定转场时的最后一次对话加载。

func loadLastMessage() {
    lastRooms = [PFObject]()
    lastUsers = [PFUser]()

    let pred = NSPredicate(format: "user1 = %@ OR user2 = %@", PFUser.currentUser(), PFUser.currentUser())

    let roomQuery = PFQuery(className: "Room", predicate: pred)
    roomQuery.orderByDescending("lastUpdate")
    roomQuery.includeKey("user1")
    roomQuery.includeKey("user2")

    roomQuery.findObjectsInBackgroundWithBlock {
        (results:[AnyObject]!, error:NSError!) -> Void in
        if error == nil{
            self.lastRooms = results as [PFObject]

            for room in self.lastRooms{
                let user1 = room.objectForKey("user1") as PFUser
                let user2 = room["user2"] as PFUser

                if user1.objectId != PFUser.currentUser().objectId {
                    self.lastUsers.append(user1)
                }

                if user2.objectId != PFUser.currentUser().objectId {
                    self.lastUsers.append(user2)
                }
            }

            let user1 = PFUser.currentUser()
            let user2 = self.lastUsers[0]

            let pred = NSPredicate(format: "user1 = %@ AND user2 = %@ OR user1 = %@ AND user2 = %@", user1, user2, user2, user1)

            let roomQuery = PFQuery(className: "Room", predicate: pred)
            roomQuery.findObjectsInBackgroundWithBlock {
                (results:[AnyObject]!, error:NSError!) -> Void in
                if error == nil{
                    let room = results.last as PFObject

                    let roomObject = NSKeyedArchiver.archivedDataWithRootObject(room)
                    NSUserDefaults.standardUserDefaults().setObject(roomObject, forKey: "kamer")

                    let userObject = NSKeyedArchiver.archivedDataWithRootObject(user2)
                    NSUserDefaults.standardUserDefaults().setObject(userObject, forKey: "andereUser")

                    NSUserDefaults.standardUserDefaults().synchronize()
                }
            }
        }
    }
}

当我尝试 unarchiveObjectWithData 作为 PFObject 它让我崩溃!

-[PFUser setObject:forKey:] 0x10ac19a9a: movq 0xb709f(%rip), %rsi ; "isEqualToString:"

我认为这与铸造有关,但我仍然没有找到解决方案。当我 println NSData 在取消存档之前,它会向我显示数据。

我认为您应该显示有关 NSKeyedUnarchiver 块的更具体的代码。所以我只能给你一些建议。

  • 检查 roomObjectuserObject 是否作为正确的 Class 取消存档。

喜欢

    var defaults = NSUserDefaults.standardUserDefaults()
    if var user = defaults.dataForKey("andereUser") {
        user_1 = NSKeyedUnarchiver.unarchiveObjectWithData(user) as? PFUser }  

那是因为 PFObject 没有实现 NSCoding 协议,所以你不能将它保存到 NSUserDefaults。