我正在尝试检索用户的数据,以使用对象ID从_User
类获取用户信息。我用过这个:
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
}
})
println(userId) // this is the userId as String.
println(self.data) ********* // empty array.
}
我在这里得到一个空数组data
..我也试过了,但同样的事情也发生在这里。 :
var profileQuery:PFQuery = PFUser.query()!
profileQuery.whereKey("objectId", equalTo: userId)
profileQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.data.addObject(object)
}
}
}
答案 0 :(得分:1)
请记住“findObjectsInBackgroundWithBlock”发生异步!您需要在块内部放置与数据相关的任何逻辑。
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
println(self.data) //shouldn't be empty.
}
})
答案 1 :(得分:0)
撇开为什么你使用NSMutableArray
作为单个PFUser
对象的原因 - 你基本上希望看到self.data
填充在错误的位置。用户将被添加到它(假设成功检索),内部闭包。所以做一些像:
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var profileQuery:PFQuery = PFUser.query()!
profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
if error == nil {
self.data.addObject(objects!)
println(self.data) //...shouldn't be empty here
} else {
println("Error retrieving user: \(error.description")
}
})
}