Blocks

Block literal

^{
    NSLog(@"This is a block");
}

As a local variable

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

// Declare
void (^simpleBlock)(void);

// Assign
simpleBlock = ^{
    ...
};

// Invoke
simpleBlock();

As a property

You should specify copy as the property attribute because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.

As a method parameter and argument

As a typedef

__block

Use __block to change the value of a captured variable from within a block.

Avoid Strong Reference Cycles when Capturing self

Blocks maintain strong references to any captured objects, including self, which means that it’s easy to end up with a strong reference cycle.

To avoid this problem, it’s best practice to capture a weak reference to self, like this:

Last updated

Was this helpful?