Skip to content

Instantly share code, notes, and snippets.

@torsten
Created June 12, 2012 13:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save torsten/2917618 to your computer and use it in GitHub Desktop.
Experiment if __block causes a retain.
// 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