Fire method when returning the last block

How do I run the method when I am sure that both block codes have returned? 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{
}

      

+3


source to share


1 answer


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

.

-(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 a guarantee of the same thread, you can use lock to make sure that the variable increment (and comparison with 2) is atomic.

+4


source







All Articles