Custom completion block for my own method

Objective CObjective C-Blocks

Objective C Problem Overview


I have just discovered completion blocks:

 completion:^(BOOL finished){
                         

                     }];

What do I need to do to have my own method take a completion block?

Objective C Solutions


Solution 1 - Objective C

1) Define your own completion block,

typedef void(^myCompletion)(BOOL);

2) Create a method which takes your completion block as a parameter,

-(void) myMethod:(myCompletion) compblock{
    //do stuff
    compblock(YES);
}

3)This is how you use it,

[self myMethod:^(BOOL finished) {
    if(finished){
        NSLog(@"success");
    }
}];

enter image description here

Solution 2 - Objective C

You define the block as a custom type:

typedef void (^ButtonCompletionBlock)(int buttonIndex);

Then use it as an argument to a method:

+ (SomeButtonView*)buttonViewWithTitle:(NSString *)title 
                          cancelAction:(ButtonCompletionBlock)cancelBlock
                      completionAction:(ButtonCompletionBlock)completionBlock

When calling this in code it is just like any other block:

[SomeButtonView buttonViewWithTitle:@"Title"
                       cancelAction:^(int buttonIndex) {
                             NSLog(@"User cancelled");
                   } 
                     completionAction:^(int buttonIndex) {
                             NSLog(@"User tapped index %i", buttonIndex);
                   }];

If it comes time to trigger the block, simply call completionBlock() (where completionBlock is the name of your local copy of the block).

Solution 3 - Objective C

Block variables are similar in syntax to function pointers in C.

Because the syntax is ugly they are often typedefed, however they can also be declared normally.

typedef void (^MyFunc)(BOOL finished);

- (void)myMethod:(MyFunc)func
{
}

See this answer for non typedef:

https://stackoverflow.com/questions/5486976/declare-a-block-method-parameter-without-using-a-typedef

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2206906View Question on Stackoverflow
Solution 1 - Objective CThilina Chamath HewagamaView Answer on Stackoverflow
Solution 2 - Objective CjszumskiView Answer on Stackoverflow
Solution 3 - Objective CJustin MeinersView Answer on Stackoverflow