有个 API 如下:
+ (void)updateByUser:(ALUser *)user completion:(void (^)(void))completion
{
AVQuery *query = [AVQuery queryWithClassName:@"Feed"];
query.limit = 15;
[query orderByDescending:@"createdAt"];
[query whereKey:@"user" equalTo:[AVObject objectWithoutDataWithClassName:@"User" objectId:user.objectId]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (AVObject *feed in objects) {
[self saveFeed:feed];
}
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
} else {
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
}
一次调用如下:
[ALFeed updateByUser:user completion:^{
[self.tableView reloadData];
}];
但如果需要多次调用后再执行回调:
for (ALUser *user in users) {
[ALFeed updateByUser:user completion:^{
}];
}
如何在所有 updateByUser:completion: 执行完后,再执行 [self.tableView reloadData];
?
JavaScript 可以用 promise 库(比如 bluebird )解决这样的问题:
var files = [];
for (var i = 0; i < 100; ++i) {
files.push(fs.writeFileAsync("file-" + i + ".txt", "", "utf-8"));
}
Promise.all(files).then(function() {
console.log("all the files were created");
});
但在 Objective-C 中,如何解决?
1
hustlzp OP 已解决,原来 GCD 中有个 dispatch_group 是专门解决这种问题的...
看来得找个时间专门学习 GCD ... ```objc dispatch_group_t group = dispatch_group_create(); for (ALUser *user in self.users) { dispatch_group_enter(group); [ALFeed updateByUser:user completion:^{ dispatch_group_leave(group); }]; } dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ [self.tableView reloadData]; }); ``` 参考: * [Waiting on Groups of Queued Tasks]( https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW25) * [Using dispatch groups to wait for multiple web services]( http://commandshift.co.uk/blog/2014/03/19/using-dispatch-groups-to-wait-for-multiple-web-services/)。 |
2
yellowV2ex 2015-10-15 13:50:14 +08:00
简单点的做法,搞个静态变量记录一下?
|
3
arkilis 2015-10-15 13:59:24 +08:00 1
or you can use NSOperation depends
|
4
hustlzp OP @yellowV2ex 每执行完就+1 ,然后观察这个数,当达到预定值时就表示所有都执行完毕?恩,这样应该可以。
|
6
jesse_luo 2015-10-15 14:11:36 +08:00
dispatch_group 应该是最简单的吧
|
7
matsuijurina 2015-10-15 14:17:35 +08:00 via iPad 1
如果你习惯了 promise...then...可以试一下 promisekit 这个库
|
9
hustlzp OP @matsuijurina 。。。 promise 无处不在啊。。。
|
10
onevcat 2015-10-15 14:32:17 +08:00 2
-.- ReactiveCocoa , combineLatest
好吧,直接 dispatch_group 多好.. |
12
chaoxn 2015-10-15 14:44:44 +08:00
喵大~
|
13
ibcker 2015-10-15 14:48:00 +08:00 1
dispatch_group or 信号量
|
14
fhefh 2015-10-15 15:22:58 +08:00
记录下 嘿嘿
|
15
rannie 2015-10-15 16:07:10 +08:00 1
dipatch_group 或者 rac signal
|
17
yongSir 2015-10-15 17:01:23 +08:00
2 个方法
用调度组 或者 在 operation 中使用 barrier block |
18
loveuqian 2015-10-15 17:20:56 +08:00 via iPhone
线程添加依赖也可以嘛?
|
19
LINAICAI 2015-10-15 17:38:57 +08:00
NSOpention 依赖也可以
|
20
newtonisaac 2015-10-15 18:01:11 +08:00
promise when
|
22
jesse_luo 2015-10-15 20:09:22 +08:00
用 semaphore 硬卡……
|