我需要使用不同的用户填充数组'从Parse.com检索的数据。使用getFirstObject
显然不是一个好主意,但我不知道如何找出每个用户获取所有数据的时间:
myObjects = []
for user in users { // users is an array of PFUsers
let query = PFQuery(className: "MyClass")
query.whereKey("asdh74tbf", equalTo: user)
query.getFirstObjectInBackgroundWithBlock{ (object: PFObject!, error: NSError!) -> Void in
if let object = object {
self.myObjects.append(object)
} else {
// handle error
}
}
}
我想在检索完所有对象后执行self.tableView.reloadData()
。怎么做?
答案 0 :(得分:3)
使用调度组。检查"等待排队任务组中的here"了解更多信息。
您还提到要获取每个用户的所有对象。因此,您可以使用findObjectsInBackgroundWithBlock方法代替getFirstObject。该块返回已解析的响应。因此,将此代码与调度组相结合,您的代码可能看起来像这样
//create a new dispatch group
let group: dispatch_group_t = dispatch_group_create();
var myObjects = []
for user in users { // users is an array of PFUsers
let query = PFQuery(className: "MyClass")
query.whereKey("asdh74tbf", equalTo: user)
//enter the dispatch group
dispatch_group_enter(group);
query.findObjectsInBackgroundWithBlock{ (objects: NSArray!, error: NSError!) -> Void in
if let object = object {
self.myObjects.append(object)
} else {
// handle error
}
//leave the dispatch group
dispatch_group_leave(group);
}
}
//will be called when all the async operations entered in the group are finished.
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
self.tableView.reloadData()
});