Skip to content

Instantly share code, notes, and snippets.

@aquarius
Created November 28, 2011 10:16
Show Gist options
  • Save aquarius/1399872 to your computer and use it in GitHub Desktop.
Save aquarius/1399872 to your computer and use it in GitHub Desktop.
What is the best way to get notified when all callbacks have returned?
for (myObject in objects) {
[myObject doWithCallback: ^(BOOL success){
//
}];
}
@anlumo
Copy link

anlumo commented Nov 28, 2011

__block NSUInteger counter = 0;
NSUInteger max = [objects count];

dispatch_queue_t q = dispatch_queue_create("com.mindnode.fafnerqueue", DISPATCH_QUEUE_SERIAL);

for (myObject in objects) {
    [myObject doWithCallback: ^(BOOL success){
        dispatch_async(q, ^{
            if(++counter >= max) {
                // Done!
                dispatch_release(q);
            }
    }];
}

@anlumo
Copy link

anlumo commented Nov 28, 2011

Alternative (probably more efficient):

__block volatile int64_t counter = 0;
int64_t max = (int64_t)[objects count];

for (myObject in objects) {
    [myObject doWithCallback: ^(BOOL success){
        if(OSAtomicIncrement64Barrier(&counter) >= max) {
            // Done! Will only be executed once.
        }
    }];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment