Note About Block in Objective-c

Here are some notes about __block in Objective-c.

  • __block is used to make a variable be mutable when used inside a block. Consider this code:
1
2
3
4
5
6
7
NSString* text = "hello";

(void)(^myBlock)() = ^void {
  NSLog(@"Text = %@", text);
};

myblock(); // "Text = hello"

This code print text when the block is called.

1
2
3
4
5
6
7
8
9
NSString* text = "hello";

(void)(^myBlock)() = ^void {
  NSLog(@"Text = %@", text);
};

text = @"good morning";

myblock(); // "Text = hello"

When there is an assignment before the block is called, the changed value does not effect the value remembered in myBlock scope. This is because when myBlock is compiled, text is captured as a constant. Thus, text value is the same no matter how the value of text is changed.

To make the value of text in the block changed, we can do by adding __block identifier.

1
2
3
4
5
6
7
8
9
__block NSString* text = "hello";

(void)(^myBlock)() = ^void {
  NSLog(@"Text = %@", text);
};

text = @"good morning";

myblock(); // "Text = good morning"
  • When debug inside the block, the variables that are not refered inside the block scope can not be inspected (inside the debugging console, by the po command).

Comments