Blocks in objective C are really awesome...but...
If you need to capture self in a block, such as when defining a callback block, it’s important to consider the memory management implications.
Blocks maintain strong references to any captured objects, including self, which means that it’s easy to end up with a strong reference cycle if, for example, an object maintains a copy property for a block that captures 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 if, for example, an object maintains a copy property for a block that captures self:
1 2 3 4 5 6 7 8 9 10 11 12 | @interface TechClass : NSObject @property (copy) void (^block)(void); @end @implementation TechClass - (void)configureBlock { self.block = ^{ [self doWork]; // capturing a strong reference to self // creates a strong reference cycle }; } @end |
To avoid this retain cycle we have to do changes as below
1 2 3 4 5 6 7 | - (void)configureBlock { TechClass * __weak weakSelf = self; self.block = ^{ [weakSelf doWork]; // capture the weak reference // to avoid the reference cycle } } |
This change makes sure that retain cycle is not created for self.
You can check all these scenario in sample code @ Sample Code