Skip to content

Instantly share code, notes, and snippets.

@landonf
Created May 22, 2010 17:38
Show Gist options
  • Save landonf/410229 to your computer and use it in GitHub Desktop.
Save landonf/410229 to your computer and use it in GitHub Desktop.
Demonstrates how -copy and -retain are handled for different block types (stack, heap, global).
/*
* Demonstrates how -copy and -retain are handled for different block types (stack, heap, global).
*/
#import <Foundation/Foundation.h>
/* print a block -description to stdout */
void PrintBlock (NSString *name, id b) {
NSString *str;
str = [NSString stringWithFormat: @"%@ (%@):\n\t-retain\t%@\n\t-copy\t%@\n\n", b, name, [[b retain] autorelease], [[b copy] autorelease]];
printf("%s", [str UTF8String]);
};
int main (int argc, char *argv[]) {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
/* Stack block */
int captured = 1;
PrintBlock(@"Stack", ^{ return captured; });
/* Heap block */
PrintBlock(@"Heap", [[^{ return captured; } copy] autorelease]);
/* Global block */
PrintBlock(@"Global", ^{});
[pool drain];
return 0;
}
@landonf
Copy link
Author

landonf commented May 22, 2010

Example output:

<NSStackBlock: 0x7fff5fbff580> (Stack):
-retain <NSStackBlock: 0x7fff5fbff580>
-copy <NSMallocBlock: 0x10010dd20>

<NSMallocBlock: 0x10010e910> (Heap):
-retain <NSMallocBlock: 0x10010e910>
-copy <NSMallocBlock: 0x10010e910>

<NSGlobalBlock: 0x100001140> (Global):
-retain <NSGlobalBlock: 0x100001140>
-copy <NSGlobalBlock: 0x100001140>

@landonf
Copy link
Author

landonf commented May 22, 2010

The take-away:

Stack Block:
-retain is a no-op
-copy returns a heap-allocated copy of the receiver

Heap Block:
-retain increments the receiver's reference count.
-copy calls -retain

Global Block (no captured variables):
-retain is a no-op
-copy is a no-op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment