Skip to content

Instantly share code, notes, and snippets.

@AlanQuatermain
Created August 2, 2011 13:57
Show Gist options
  • Save AlanQuatermain/1120236 to your computer and use it in GitHub Desktop.
Save AlanQuatermain/1120236 to your computer and use it in GitHub Desktop.
Sample code to illustrate different types of blocks— global. heap, and stack.
//
// main.m
// BlocksRuntime
//
// Created by Jim Dovey on 11-07-22.
// Copyright 2011 Jim Dovey. All rights reserved.
//
#import <Foundation/Foundation.h>
// from Block_private.h in libclosure for Lion
extern const char * _Block_dump(const void *block);
typedef void (^test_block_t)(int i);
static void global_block_example(void)
{
printf("\n\nGLOBAL BLOCKS\n\n");
// this block will be made global because it doesn't pull in any values from the stack,
// thus causing the compiler to allocate it globally.
test_block_t block = ^(int i) {
printf("Pure global block was passed %d\n", i);
};
block(42);
printf("This is the pure global block's debug information before copy:\n%s\n",
_Block_dump((__bridge const void *)block));
block = [block copy]; // using ObjC methods so ARC can clean it up
printf("This is the pure global block's debug information after copy:\n%s\n",
_Block_dump((__bridge const void *)block));
}
static void heap_block_example(void)
{
printf("\n\nHEAP BLOCKS\n\n");
__block int j = 27;
// this block will be allocated on the heap since it uses a __block variable and isn't outside
test_block_t globalBlock = ^(int i) {
printf("Global block with __block variable was passed %d\n", i);
j += i;
};
globalBlock(42);
printf("After running the block, j is %d\n", j);
globalBlock(87);
printf("After running the block, j is %d\n", j);
printf("This is the debug information of a global block with a __block argument before copy:\n%s\n",
_Block_dump((__bridge const void *)globalBlock));
globalBlock = [globalBlock copy];
printf("This is the debug information of a global block with a __block argument after copy:\n%s\n",
_Block_dump((__bridge const void *)globalBlock));
}
static void stack_block_example(dispatch_block_t block)
{
printf("\n\nSTACK BLOCKS\n\n");
printf("This is the debug information of a passed-in stack-based block:\n%s\n",
_Block_dump((__bridge const void *)block));
block();
block = [block copy];
printf("This is the debug information of a copied stack-based block:\n%s\n",
_Block_dump((__bridge const void *)block));
block();
}
int main (int argc, const char * argv[])
{
@autoreleasepool
{
printf("This is an inline block's debug information:\n%s\n", _Block_dump((__bridge const void *)^{
printf("I am an inline block.\n");
}));
global_block_example();
heap_block_example();
stack_block_example(^{
printf("Inline stack (?) block: argc = %d\n", argc);
});
}
return ( 0 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment