Objective-C Language Blocks Blocks as Properties

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

@interface MyObject : MySuperclass

@property (copy) void (^blockProperty)(NSString *string);

@end

When assigning, since self retains blockProperty, 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 highly unlikely, but self might be deallocated inside the block, somewhere during the execution. In this case weakSelf becomes nil and all messages to it have no desired effect. This might leave the app in an unknown state. This can be avoided by retaining weakSelf with a __strong ivar during block execution and clean up afterward.

__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;
};


Got any Objective-C Language Question?