Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire Method When Last Block Returns

Tags:

ios

block

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{
}
like image 842
Alan Avatar asked Nov 25 '25 19:11

Alan


1 Answers

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.

like image 93
carlosfigueira Avatar answered Nov 28 '25 17:11

carlosfigueira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!