Created
June 12, 2012 13:50
-
-
Save torsten/2917618 to your computer and use it in GitHub Desktop.
Experiment if __block causes a retain.
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
// Run with: | |
// clang -fobjc-arc -Wall -framework Foundation blockself.m && ./a.out | |
// Further reading: | |
// http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html | |
// http://clang.llvm.org/docs/AutomaticReferenceCounting.html#misc.blocks | |
// http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html | |
#import <Foundation/Foundation.h> | |
#pragma clang diagnostic ignored "-Warc-performSelector-leaks" | |
static SEL retainCount; | |
typedef void (^BlockType)(); | |
int main(int argc, char *argv[]) | |
{ | |
retainCount = sel_registerName("retainCount"); | |
@autoreleasepool | |
{ | |
NSString *str = [NSString stringWithFormat:@"f%d", 0]; | |
printf("initial retainCount: %ld\n", (long)[str performSelector:retainCount]); | |
// This does retain: | |
#if 0 | |
BlockType block = ^() | |
{ | |
printf("executed in block retainCount: %ld\n", (long)[str performSelector:retainCount]); | |
}; | |
block(); | |
// Only __unsafe_unretained does not retain in these cases: | |
#else | |
__block NSString *selfStr = str; | |
// __weak NSString *selfStr = str; | |
// __unsafe_unretained NSString *selfStr = str; | |
BlockType block = ^() | |
{ | |
printf("executed in self block retainCount: %ld\n", (long)[selfStr performSelector:retainCount]); | |
}; | |
block(); | |
#endif | |
printf("final retainCount: %ld\n", (long)[str performSelector:retainCount]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment