Custom completion block for my own method

I just opened the completion blocks:

completion:^(BOOL finished){ }]; 

What do I need to do so that my own method takes a completion block?

+68
objective-c objective-c-blocks
May 01 '13 at 18:30
source share
3 answers

1) Define your own completion block,

 typedef void(^myCompletion)(BOOL); 

2) Create a method that 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

+211
May 01 '13 at 18:36
source share

You define the block as a custom type:

 typedef void (^ButtonCompletionBlock)(int buttonIndex); 

Then use it as an argument to the method:

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

When calling this code, it is like any other block:

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

If it's time to start the block, just call completionBlock() (where completionBlock is the name of your local copy of the block).

+23
May 01 '13 at 18:36
source share

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

Because the syntax is ugly, they are often typed, however they can also be declared as usual.

 typedef void (^MyFunc)(BOOL finished); - (void)myMethod:(MyFunc)func { } 

See this answer for non typedef:

Declare a block method parameter without using typedef

+2
May 01 '13 at 18:34
source share



All Articles