Skip to content

Instantly share code, notes, and snippets.

@randomsequence
Last active December 16, 2015 09:29
Show Gist options
  • Save randomsequence/5413480 to your computer and use it in GitHub Desktop.
Save randomsequence/5413480 to your computer and use it in GitHub Desktop.
Capturing an ivar in a block also captures self
// Code as written:
@interface MyClass : NSObject {
NSObject *_ivar;
}
@end
@implementation MyClass
- (void)logStuff {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"ivar: %@", _ivar);
});
}
@end
// What I thought happened
@interface MyClass : NSObject {
NSObject *_ivar;
}
@end
@implementation MyClass
- (void)logStuff {
__strong id ivar = _ivar;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"ivar: %@", ivar);
});
}
@end
// What actually happens:
@interface MyClass : NSObject {
NSObject *_ivar;
}
@end
@implementation MyClass
- (void)logStuff {
__strong id capturedSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"ivar: %@", capturedSelf->_ivar);
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment