Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom completion block for my own method [duplicate]

I have just discovered completion blocks:

 completion:^(BOOL finished){                        }]; 

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

like image 909
user2206906 Avatar asked May 01 '13 18:05

user2206906


2 Answers

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

like image 195
Thilina Chamath Hewagama Avatar answered Sep 22 '22 14:09

Thilina Chamath Hewagama


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).

like image 38
jszumski Avatar answered Sep 21 '22 14:09

jszumski