How to write an Objective-C Completion Block
I always use this when I want to write a block:
EDIT
If you are writing Swift then use this:
http://fuckingswiftblocksyntax.com
If the above links are not opening because of the obscene language, use this one.
I wrote a completionBlock for a class which will return the values of a dice after they have been shaked:
Define typedef with returnType (
.h
above@interface
declaration)typedef void (^CompleteDiceRolling)(NSInteger diceValue);
Define a
@property
for the block (.h
)@property (copy, nonatomic) CompleteDiceRolling completeDiceRolling;
Define a method with
finishBlock
(.h
)- (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))finishBlock;
Insert previous defined method in
.m
file and commitfinishBlock
to@property
defined before- (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))finishBlock{ self.completeDiceRolling = finishBlock;}
To trigger
completionBlock
pass predefined variableType to it (Don't forget to check whether thecompletionBlock
exists)if( self.completeDiceRolling ){ self.completeDiceRolling(self.dieValue);}
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