gpt4 book ai didi

iphone - NSArray enumerateObjectsUsingBlock : delay enumeration

转载 作者:行者123 更新时间:2023-11-29 11:04:29 25 4
gpt4 key购买 nike

我使用快速枚举并在枚举 block 中异步发送网络请求。

那么 enumerateObjectsUsingBlock 会发生什么:只需超快地调用 block 并让枚举 block 在一段时间后完成。

这会导致不同的结果,因为有些请求比其他请求完成得更快。所以它没有按我想要的方式排序。

有没有办法设置 block 卡住,异步网络请求完成后,只告诉它去下一个?

代码如下

    NSArray *sites = [self.fetchedResultsController.fetchedObjects copy];
NSLog(@"sites - %@",sites);
[sites enumerateObjectsUsingBlock:^(Sites *site, NSUInteger idx, BOOL *stop) {
NSLog(@"site name - %@,",site.name);

[[Wrapper sharedWrapper] sendRequestTo:site completionBlock:{

NSLog(@"site name - %@",site.name);
}];
}];

谢谢!

最佳答案

Is there any way to set the block to freeze, and after the asynchronous network requests is completed, to just tell it to go to the next one?

NSArray *sites = [self.fetchedResultsController.fetchedObjects copy];
NSLog(@"sites - %@",sites);
[sites enumerateObjectsUsingBlock:^(Sites *site, NSUInteger idx, BOOL *stop) {
NSLog(@"site name - %@,",site.name);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[Wrapper sharedWrapper] sendRequestTo:site completionBlock:{

NSLog(@"site name - %@",site.name);
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}];

^ 这不是真正理想的方法,但如果你想在等待异步请求完成的同时进行同步迭代,然后再继续,上面的方法将通过 GCD 完成。还有其他方法可以在等待异步任务完成后离开所有组的同时迭代和递增 dispatch_group,例如:

dispatch_group_t downloadGroup = dispatch_group_create();


dispatch_group_enter(downloadGroup);
[self fetchStuffInBackground:background withCompletion:^(NSArray *stuff, NSError *error) {
NSLog(@"leaving stuff");
dispatch_group_leave(downloadGroup);
}];
dispatch_group_enter(downloadGroup);
[self fetchAOtherStuffInBackground:background withCompletion:^(NSArray *stuff, NSError *error) {
NSLog(@"leaving other stuff");
dispatch_group_leave(downloadGroup);
}];
dispatch_group_enter(downloadGroup);
[self fetchLastStuffInBackground:background withCompletion:^(NSArray *lastStuff, NSError *error) {
NSLog(@"leaving last stuff");
dispatch_group_leave(downloadGroup);
}];
}

}
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
if (callback) {
callback(error);
}
});

关于iphone - NSArray enumerateObjectsUsingBlock : delay enumeration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14292027/

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