Search code examples
iosblock

Fire Method When Last Block Returns


How I do fire a method when I am confident both block codes have returned? Like so...

// Retrieve Messages Array from Parse
[ParseManager retrieveAllMessagesForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){
        self.messagesArray = objects;
    }];

// Retrieve MessagesPermissions Array from Parse
[ParseManager retrieveAllMessagePermissionsForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){
        self.messagePermissionsArray = objects;
    }];

-(void)methodToRunWhenBothBlocksHaveReturned{
}

Solution

  • If you can guarantee that the blocks will be executed on the same thread (i.e., the UI thread), then the alternative is simple, using a __block variable.

    -(void)yourMethod {
        __block int count = 0;
        [ParseManager retrieveAllMessagesForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){
            self.messagesArray = objects;
            count++;
            if (count == 2) {
                 [self methodToRunWhenBothBlocksHaveReturned];
            }
        }];
    
        [ParseManager retrieveAllMessagePermissionsForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){
            self.messagePermissionsArray = objects;
            count++;
            if (count == 2) {
                 [self methodToRunWhenBothBlocksHaveReturned];
            }
        }];
    }
    
    -(void)methodToRunWhenBothBlocksHaveReturned{
    }
    

    If you don't have the same-thread guarantee, you can use a lock to make sure that the increment of the variable (and the comparison to 2) will be atomic.