将 PFObject 附加到数组,结果所有元素都被替换(Swift,解析)

Append PFObject to Array resulting all elements replaced (Swift, Parse)

我正在使用 Parse 设置用户对并将 matchedRelation 保存在 UserRelations class 中。但是,我发现一个奇怪的问题,当将 PFObject 附加到 PFObject 数组时,该数组中的所有元素都将被替换,而使用 AnyObject 数组时完全没问题。请帮我找出问题所在。

query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            var pairRelation = PFObject (className: "UserRelations")
            var pairRelations = [PFObject]()
            var testArray = [AnyObject]()

            for object in objects {

                pairRelation.setObject(object.username, forKey: "toUser")
                pairRelation.setObject(PFUser.currentUser()!, forKey: "fromUser")
                pairRelation.setObject(true, forKey: "isMatched")

                pairRelations.append(pairRelation)
                testArray.append(object.username)

                println("After append the results of the Array is: \(pairRelations)")
                println("\nAfter append the results of the test Array is: \(testArray)")

            }
        } 
    }

前三场比赛的输出如下所示:

After append the results of the Array is: [<UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "asdfsdf@df.sdfss";}, <UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "asdfsdf@df.sdfss";}, <UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "asdfsdf@df.sdfss";}]

After append the results of the test Array is: 
[andy@gd.com, dfasdf@fsadf.dfs, asdfsdf@df.sdfss]

所以 PFObject 数组在附加后都得到了相同的元素,而另一个数组得到了所有三个不同的用户。感谢任何 comment/help!

您目前正在创建一个名为 pairRelationPFObject 实例。所以在你的循环中你总是更新内存中的同一个对象。

只需将该行移动到循环中,这样每次都可以创建一个新的 PFObject:

query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            var pairRelations = [PFObject]()
            var testArray = [AnyObject]()

            for object in objects {
                var pairRelation = PFObject (className: "UserRelations") //Create new PFObject

                pairRelation.setObject(object.username, forKey: "toUser")
                pairRelation.setObject(PFUser.currentUser()!, forKey: "fromUser")
                pairRelation.setObject(true, forKey: "isMatched")

                pairRelations.append(pairRelation)
                testArray.append(object.username)

                println("After append the results of the Array is: \(pairRelations)")
                println("\nAfter append the results of the test Array is: \(testArray)")

            }
        } 
    }