Objective-C块和变量
栏目: Objective-C · 发布时间: 7年前
内容简介:翻译自:https://stackoverflow.com/questions/12863648/objective-c-blocks-and-variables
我今天开始使用Objective-C块.我写了以下代码:
NSArray *array = @[@25, @"abc", @7.2];
void (^print)(NSUInteger index) = ^(NSUInteger index)
{
NSLog(@"%@", array[index]);
};
for (int n = 0; n < 3; n++)
print(n);
哪个工作正常.我需要在声明后更改数组变量,所以我尝试使用以下代码:
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)三次.为什么这不起作用,而它确实与我的第一段代码一起工作?
注意:我知道这是一种非常低效的方法来打印我的数组的三个值,但这不是我的原始代码.我碰到了这个问题并尝试将其分解以查明问题所在.
这是因为块按值捕获变量以及何时创建块(除非使用__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的效率会低一些.
翻译自:https://stackoverflow.com/questions/12863648/objective-c-blocks-and-variables
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Writing Windows VxDs and Device Drivers, Second Edition
Karen Hazzah / CMP / 1996-01-12 / USD 54.95
Software developer and author Karen Hazzah expands her original treatise on device drivers in the second edition of "Writing Windows VxDs and Device Drivers." The book and companion disk include the a......一起来看看 《Writing Windows VxDs and Device Drivers, Second Edition》 这本书的介绍吧!