2

最近,我试图调试一些代码,我对自己做错了什么感到困惑。我的问题的简化版本如下:

for(int x = 0; x < [myArray count]; x++);
{
    //perform some action
}

问题是我想要执行的操作只会发生一次。当然,我最终注意到问题是我不小心在 for 循环的末尾包含了一个额外的分号。

for(int x = 0; x < [myArray count]; x++);<---- Oops!
{
    //perform some action
}

但后来我想知道......为什么该代码甚至可以工作?事实证明,我的 for 循环正在执行,然后下面的代码作为“匿名块”运行。

  1. Objective C 中匿名块的意义何在?它们何时/何地有用?

  2. 为什么我的代码不会在 Xcode 中生成某种警告?我想您可以将任何旧代码部分放在一对额外的大括号中,然后突然将其作为匿名块执行?

4

2 回答 2

6

它们可用于确定变量的范围。虽然它更像是一个排版的东西,但当您需要自定义一系列相同类型的对象时,它可以很方便,允许您重复使用相同的变量。例如说你正在设置一些NSURLRequests

NSMutableArray *requests = [NSMutableArray array];
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    request.URL = [NSURL URLWithString:@"http://A"];
    request.HTTPMethod = @"GET";
    [requests addObject:request];
}
// ... etc
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    request.URL = [NSURL URLWithString:@"http://Z"];
    request.HTTPMethod = @"POST";
    [requests addObject:request];
}
于 2012-10-04T17:54:08.157 回答
0

Turn on CLANG_WARN_EMPTY_BODY and you'll get a warning for this. You should really go through all the warnings that can be enabled in Xcode and turn on everything that is useful (everything that doesn't give lots of warnings for code that is perfectly fine).

The feature itself was present in the very first C versions in the late 1970's.

And never heard this being called an "anonymous block". It's a compound statement. Sometimes it is called a block, but I've never heard the term "anonymous block".

于 2014-04-27T13:17:36.240 回答