Objective-C blocks and variables

我是研究僧i 提交于 2020-01-02 02:01:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12863648/objective-c-blocks-and-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!