Clicky

iOS Dev Nugget 40 Blocks are Great, but Watch Out for Retain Cycles

.

Need to run a code review on your codebase? Hire me

Blocks are wonderful and in many cases lead to shorter code, e.g. reducing callback and multithreading code. But it's also easy to create retain cycles when you use blocks, causing memory to be unnecessarily retained. Retain cycles happen when — in the simplest and most common case, two — objects keep strong references to each other such that they can't be freed even when the objects aren't used anymore.

-someMethod1 will cause a retain cycle. The block refers to self (an instance of SomeClass) and will retain a strong reference to the instance of SomeClass, which also retains a strong reference to the block. -someMethod2 is the correct way to write the code. It breaks the retain cycle by forcing the block to only access a weak reference to the instance of SomeClass.

@interface SomeClass()
@property (nonatomic,strong) MyClass* obj;
@end

@implementation SomeClass

- (void)someMethod1 {
    self.obj = [MyClass new];
    self.obj.block = ^{
        //use self
    };
}

- (void)someMethod2 {
    self.obj = [MyClass new];
    __weak typeof(self) weakself = self;
    self.obj.block = ^{
        //use weakself instead of self
    };
}

@end

Current versions of Xcode (4.6.2 as of writing) warns about this, but it is useful to know especially to be able to look out for more complicated cases where the compiler cannot detect this.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues