Подождите, пока не будут выполнены все несколько сетевых запросов, включая их блоки завершения.

У меня есть несколько операций (это запросы AFNetworking) с блоками завершения, выполнение которых занимает некоторое время, и объект Core Data, который необходимо сохранить в конце всех запросов.

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, моя очередь блокирует текущий поток до тех пор, пока мои запросы не будут завершены, но не до тех пор, пока не будут завершены мои блоки успеха, что действительно мне нужно.

Есть идеи, как добиться этого хорошим способом?

39
задан Josh Caswell 18 February 2015 в 23:21
поделиться