1

My situation is:

  • I have users
  • Each user has some history data that can be fetched via user objects

What I want to do is:

  • Max 2 users must be fetching their history data at the same time (this is the reason that I want to use NSOperationQueue)
  • I need to get notified when any user finished fetching its history data
  • I need to get notified when every user finished fetching their history data

What I ask is:

  • How can I achieve what I want to do since I can't make it thru with the code below?

Any help is appreciated.

    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue setMaxConcurrentOperationCount:2];

    for (User *user in users) {
        NSBlockOperation *operationObject = [NSBlockOperation blockOperationWithBlock:^{
            [user loadHistoryData:^{
                [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
            }];
        }];

        [operationQueue addOperation:operationObject];
    }

This question differs from this question because I don't want to chain any requests. I just want to know when they are all finished executing.

This answer has a completion block for only one operation queue.

This answer offers a way to make operation block to wait until async call to loadHistoryData is completed. As writing setSuspended

I could not find an answer for my need. Is there any?

Okhan Okbay
  • 1,304
  • 12
  • 26

2 Answers2

1

Use KVO to observe the operations property of your queue, then you can tell if your queue has completed by checking for [queue.operations count] == 0.

Somewhere in the file do the KVO in, declare a context for KVO like this (more info):

Anand Prakash
  • 470
  • 6
  • 21
0

I've used AsyncBlockOperation and NSOperationQueue+CompletionBlock

Combining them is working for me like this:

  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  [queue setMaxConcurrentOperationCount:1]; 
  // 1 is serial, more is concurrent

  queue.completionBlock = ^{
    [NSNotificationCenter postNotificationToMainThread:@"allUsersFetchedHistory"];
  };

  for (User *user in users){
   [queue addOperationWithAsyncBlock:^(AsyncBlockOperation *op) {
     [user loadHistoryData:^{
       [op complete];
       [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
      }];
    }];
  }
Okhan Okbay
  • 1,304
  • 12
  • 26