Blocks in Objective-C

Lego Blocks

For some reason I can’t get it in my head how to declare a block in Objective-C. Maybe its syntax is too complicated or my brain is blocking this style of block declaration.

There are many ways you can declare a block.

As a property,

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

Or as a method parameter,

- (void)methodThatUseABlock:(returnType (^)(parameterTypes))blockName {}

I strongly suggest to use block instead of delegates is a cleaner way to code, especially with delegates.

Or a local variable,

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {};

Or as a typedef,

typedef returnType (^TypeName)(parameterTypes);
  TypeName blockName = ^(parameters) {}

Source Reference: iOS Developer Library

Focus Mode

Contact Request

Close

We will call you right away. All information is kept private