我在PFUser数组中进行for循环,然后在for循环中我希望能够为已经循环的每个用户设置关键字段。由于某种原因,它只保存for循环中的最后一个元素。谁能解释我做错了什么?代码:
var user2ObjId = ["N7xqk8oFJx", "Q5lPX2DUmP", "mfkO8iypTB"]
let userQuery = PFUser.query()
userQuery.whereKey("objectId", containedIn: user2ObjId)
let foundUsers = userQuery.findObjects()
if foundUsers.count > 0 {
let addRoomObject = PFObject(className: "Room")
for user in foundUsers {
addRoomObject["user1"] = PFUser.currentUser()
addRoomObject["user2"] = user
addRoomObject.addObject(2, forKey: "questionNumbers")
addRoomObject["matchCount"] = 1
}
addRoomObject.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in
if success == true {
// println("Added new users to room")
}
})
}
<{1>}数组中的唯一保存的是user2ObjId
。这是为什么?
答案 0 :(得分:2)
如果查看for-in循环,则将属性设置为同一个实例,但是在退出循环时将保存,这在foundUsers
中的最后一个元素已处理时发生 - 这解释了为什么只保存最后一个对象。
您可以使用saveAllInBackground
var array = [PFObject]()
for user in foundUsers {
let addRoomObject = PFObject(className: "Room")
addRoomObject["user1"] = PFUser.currentUser()
addRoomObject["user2"] = user
addRoomObject.addObject(2, forKey: "questionNumbers")
addRoomObject["matchCount"] = 1
array.append(addRoomObject)
}
PFObject.saveAllInBackground(array, block({ (success: Bool, error: NSError!) -> Void in
if success == true {
// println("Added new users to room")
}
})