Thursday, October 22, 2015

Weak Self Objective-C in Blocks

@implementation XYZBlockKeeper
- (void)configureBlock {
self.block = ^{
[self doSomething]; // capturing a strong reference to self
// creates a strong reference cycle
};
}
...
@end
/*
It’s best practice to capture a weak reference to self, like this:
*/
- (void)configureBlock {
XYZBlockKeeper * __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething]; // capture the weak reference
// to avoid the reference cycle
}
}
view raw blocks.m hosted with ❤ by GitHub

No comments:

Post a Comment

Blog Archive