I've started using Objective-C blocks today. I wrote the following code:
NSArray *array = @[@25, @"abc", @7.2];
void (^print)(NSUInteger index) = ^(NSUInteger index)
{
NSLog(@"%@", array[index]);
};
for (int n = 0; n < 3; n++)
print(n);
Which works properly. I needed to change the array
variable after its declaration, though, so I tried using the following code:
NSArray *array;
void (^print)(NSUInteger index) = ^(NSUInteger index)
{
NSLog(@"%@", array[index]);
};
array = @[@25, @"abc", @7.2];
for (int n = 0; n < 3; n++)
print(n);
However, that doesn't work. The console just prints (null)
three times. Why is it that this doesn't work, while it did work with my first piece of code?
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .
Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part.
It's because the block captures variables by value and when the block is created (unless you use __block
).
What you probably want is:
NSArray *array = @[@25, @"abc", @7.2];
void (^print)(NSUInteger index) = ^(NSUInteger index)
{
NSLog(@"%@", array[index]);
};
for (int n = 0; n < 3; n++)
print(n);
Example with __block
:
__block NSArray *array;
void (^print)(NSUInteger index) = ^(NSUInteger index)
{
NSLog(@"%@", array[index]);
};
array = @[@25, @"abc", @7.2];
for (int n = 0; n < 3; n++)
print(n);
Note that it's a little less efficient to use __block
if you don't actually need to modify the variable inside the block and have it reflected outside.
The block captures the array
pointer at creation. You can add __block
modifier to have the block capture the pointer by reference, but this is usually costly and not recommended. It is better to have the capturing block created after the data is ready to use inside the block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With