簡體   English   中英

將PFObject附加到Array,從而替換所有元素(Swift,Parse)

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

我正在使用Parse來設置用戶對,並將matchedRelation保存在UserRelations類中。 但是,在將PFObject附加到PFObject Array時,我發現了一個奇怪的問題,該Array中的所有元素都將被替換,而使用AnyObject Array時完全沒問題。 請幫助我找出問題所在。

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數組在追加后都具有相同的元素,而花葯數組則具有所有三個不同的用戶。 感謝您的任何評論/幫助!

您當前正在創建的一個實例PFObject命名pairRelation 因此,在循環中,您總是在更新內存中的同一對象。

只需在循環中移動該行,即可每次創建一個新的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)")

            }
        } 
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM