-
-
Save jacksonfdam/2820170 to your computer and use it in GitHub Desktop.
Blocks in Objective-C
This file contains 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
- (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