gpt4 book ai didi

arrays - 将 PFObject append 到数组,导致所有元素被替换(Swift、Parse)

转载 作者:行者123 更新时间:2023-11-30 10:13:33 25 4
gpt4 key购买 nike

我正在使用 Parse 设置用户对并将matchedRelation 保存在UserRelations 类中。但是,我发现一个奇怪的问题,当将 PFObject append 到 PFObject 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 数组在追加后都获得了相同的元素,而花药数组则获得了所有三个不同的用户。感谢您的任何评论/帮助!

最佳答案

您当前正在创建一个名为 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)")

}
}
}

关于arrays - 将 PFObject append 到数组,导致所有元素被替换(Swift、Parse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com