Blocks as Properties
suggest change@interface MyObject : MySuperclass
@property (copy) void (^blockProperty)(NSString *string);
@end
When assigning, since self retains blockProperty, the block should not contain a strong reference to self. Those mutual strong references are called a “retain cycle” and will prevent the release of either object.
__weak __typeof(self) weakSelf = self;
self.blockProperty = ^(NSString *string) {
// refer only to weakSelf here. self will cause a retain cycle
};
It is possible, though uncommon, for self to be deallocated while the block is running. In that case weakSelf becomes nil, and messages to it do nothing. Avoid that by keeping a __strong local reference to weakSelf for the rest of the block.
__weak __typeof(self) weakSelf = self;
self.blockProperty = ^(NSString *string) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
// refer only to strongSelf here.
// ...
// At the end of execution, clean up the reference
strongSelf = nil;
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents