Last active
December 16, 2015 09:29
-
-
Save randomsequence/5413480 to your computer and use it in GitHub Desktop.
Capturing an ivar in a block also captures self
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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