2

在 Apple 块文档中是不要编写的代码示例:

void dontDoThisEither() {
  void (^block) (void);
  int i = random();
  if (i > 1000) {
    block = ^{printf("got i at: %d\n", i); };
  }
  // ...
}

代码的注释说块文字范围是“then”子句。我不明白他们的意思,没有 then 子句,这大概就是他们将其放在引号中的原因。但是为什么他们把它放在引号中,与块的范围有什么关系?

4

1 回答 1

2

将 if 语句想象为: if this then that else this other thing

{... block = ...}是在语句的部分。if也就是说,它是dontDoThisEither()函数作用域的一个子作用域。

因为块是在堆栈上创建的,并且仅在其声明范围内有效,这意味着该示例中的块分配仅在语句的then范围内if有效。

即考虑:

void dontDoThisEither() {
  void (^block) (void);
  int i = random();
  if (i > 1000) {
    block = ^{printf("got i at: %d\n", i); };
  }  else {
    block = ^{printf("your number is weak and small. ignored.\n");};
  }
  block();
}

block();执行时,它指向的块位于不再有效的范围内,并且行为将是未定义的(并且在现实世界的示例中可能会崩溃)。

于 2012-11-05T17:44:14.953 回答