I am using Parse to setup User pairs and save the matchedRelation in a UserRelations class. However, I found a weird issue when append a PFObject to PFObject Array, all the elements in that Array will be replaced, while it is totally fine when using AnyObject Array. Please help me find out what is wrong.
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)")
}
}
}
The output for the first three matches is shown here:
After append the results of the Array is: [<UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "[email protected]";}, <UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "[email protected]";}, <UserRelations: 0x7fe22b0713c0, objectId: new, localId: (null)> {
fromUser = "<PFUser: 0x7fe22b127670, objectId: 3WXg5FUEsE>";
isMatched = 1;
toUser = "[email protected]";}]
After append the results of the test Array is:
[[email protected], [email protected], [email protected]]
So the PFObject Array all got the same elements after appending, while the anther array got all three different users. Thanks for any comment/help!
You are currently creating one instance of your PFObject
named pairRelation
. So inside your loop you are always updating the same object in memory.
Just move that line inside your loop so that you create a new PFObject each time:
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)")
}
}
}