What you want to avoid with blocks is a retain cycle—two objects keeping each other alive unnecessarily.
If I have an object with this property:
@property (strong) void(^completionBlock)(void);
and I have this method:
- (void)doSomething
{
self.completionBlock = ^{
[self cleanUp];
};
[self doLongRunningTask];
}
the block will be kept alive when I store it in the completionBlock
property.
But since it references self
inside
the block, the block will keep self
alive
until it goes away—but this won’t happen since they’re both referencing each other.
In this method:
- (void)doSomething
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self cleanUp];
}];
[self doLongRunningTask];
}
you don’t need to make a weak reference to self
.
The block will keep self
alive,
since it references self
from
within, but since all we’re doing is handing the block off to [NSOperationQueue
mainQueue]
, self
isn’t
keeping the block alive.