我有多个操作(它们是 AFNetworking 请求),完成块需要一些时间才能执行,还有一个核心数据对象需要在所有请求结束时保存。
MyCoreDataObject *coreDataObject;
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
coreDataObject.attribute1 = responseObject;
sleep(5);
}];
[operation1 start];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
coreDataObject.attribute2 = responseObject;
sleep(10);
}];
[operation1 operation2];
[context save:nil];
当然,这并不像我想要的那样工作,因为请求是异步的。我尝试像这样添加一个 NSOperationQueue:
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:2];
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
coreDataObject.attribute1 = responseObject;
sleep(5);
}];
[operationQueue addOperation:operation1];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
coreDataObject.attribute2 = responseObject;
sleep(10);
}];
[operationQueue addOperation:operation2];
[imageQueue waitUntilAllOperationsAreFinished];
[context save:nil];
这看起来好一点。使用waitUntilAllOperationsAreFinished
,我的队列会阻塞当前线程,直到我的请求完成,但直到我的成功块完成,这才是我真正需要的。
关于如何以一种好的方式实现这一目标的任何想法?