Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Created August 19, 2011 17:39
Show Gist options
  • Save mumoshu/1157442 to your computer and use it in GitHub Desktop.
Save mumoshu/1157442 to your computer and use it in GitHub Desktop.
Blocks in Objective-C
- (void)test
{
int foo = 1;
void (^block)() = ^() {
NSLog(@"%d at %p", foo, &foo); //=> 1 at 0xbfffd65c / エンクロージャの変数fooは参照できる.
// 以下は 'Variable is not assignable' コンパイルエラー
// foo = 2;
};
block();
NSLog(@"%d at %p", foo, &foo); //=> 1 at 0xbfffd6ac / block内のfooとはアドレスが違う.
int *bar = malloc(sizeof(int));
*bar = 1;
void (^block2)() = ^() {
NSLog(@"%d at %p, address of bar is %p", *bar, bar, &bar); //=> 1 at 0x4b21d30, address of bar is 0xbfffd658
*bar = 2;
};
block2();
NSLog(@"%d at %p, address of bar is %p", *bar, bar, &bar); //=> 2 at 0x4b21d30, address of bar is 0xbfffd6a4
free(bar);
int baz = 1;
int *_baz = &baz;
void (^block3)() = ^() {
NSLog(@"%d", *_baz); //=> 1
*_baz = 2;
};
block3();
NSLog(@"%d", *_baz); //=> 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment