Objective-C块和变量 [英] Objective-C blocks and variables

查看:89
本文介绍了Objective-C块和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始使用Objective-C块.我写了以下代码:

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);

哪个工作正常.不过,我需要在声明后更改array变量,因此我尝试使用以下代码:

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);

但是,这不起作用.控制台仅打印(null)三次.为什么它在我的第一段代码中起作用却为什么不起作用?

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?

推荐答案

这是因为该块会按值捕获 创建该块时的变量(除非您使用__block).

It's because the block captures variables by value and when the block is created (unless you use __block).

您可能想要的是:

NSArray *array = @[@25, @"abc", @7.2];

void (^print)(NSUInteger index) = ^(NSUInteger index)
{
    NSLog(@"%@", array[index]);
};

for (int n = 0; n < 3; n++)
    print(n);

带有__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);

请注意,如果您实际上不需要修改块内的变量并将其反映到外部,则使用__block的效率会降低一些.

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.

这篇关于Objective-C块和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆