【问题标题】:Value of loop variable after "for in" loop in Objective CObjective C中“for in”循环后循环变量的值
【发布时间】:2013-09-29 13:01:14
【问题描述】:

只要循环不包含 break 语句,循环执行后for - in 循环中的循环变量的值是否保证为 nil?例如,我想编写如下代码:

NSArray *items;
NSObject *item;
for (item in items) {
   if (item matches some criterion) {
      break;
   }
}
if (item) {
   // matching item found. Process item.
}
else {
   // No matching item found.
}

但是当 for 循环一直运行而没有 break 时,此代码依赖于将 item 设置为 nil

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    另一种解决方案是检查通过特定测试的数组对象。您似乎在第一次出现时就中断了,所以我也只能得到一个索引。如果您想要所有匹配项,您可以改用indexesOfObjectsPassingTest:

    NSUInteger index = [items indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if (/* check the item*/) {
            *stop = YES;
        }
    }];
    
    if (index == NSNotFound) {
        // no match was found
    } else {
        // at least one item matches the check
        id match = items[index];
    }
    

    【讨论】:

    • 用 arc all 自动归零
    • 这看起来不错,谢谢,但看起来你必须在中断时设置 matchingItem 的值,就像 bneely 的回答一样。
    • @Daij-Djan 你是对的,现在假设 ARC 可能是安全的,但我仍然觉得这是一个很好的做法。仍然需要指出的是,它会为您设置为零。
    • @David Rönnqvist 我的评论提到了您答案的早期版本,其中出现了变量“matchingItem”。看来你已经把它删掉了,所以我的评论不再适用。
    • @WillNelson 哦,对不起。我没有意识到这一点。
    【解决方案2】:

    你应该改用这个:

    id correctItem = nil;
    for (id item in items) {
        if (item matches some criteria) {
            correctItem = item;
            break;
        }
    }
    

    【讨论】:

    • 用 arc all 自动归零
    • 谢谢,这符合我的要求。
    【解决方案3】:

    启用 ARC 后,无论您在何处创建它们,您的 Objective-C 对象指针变量都将设置为 nil。 [Source]

    如果你不使用 ARC,你可以将指针显式赋值为 nil:

    NSArray *items;
    NSObject *item = nil;  //<- Explicitly set to nil
    for (item in items) {
       if (item matches some criterion) {
          break;
       }
    }
    if (item) {
       // matching item found. Process item.
    }
    else {
       // No matching item found.
    }
    

    我不知道确切的情况,但你不能这样做,在 for 循环中进行 工作:

    NSArray *items;
    NSObject *item; //Doesn't really matter about item being set to nil here.
    for (item in items) {
       if (item matches some criterion) 
       {
           // matching item found. Process item.
          break;
       }
    }
    //Don't have to worry about item after this
    

    【讨论】:

    • 当您将要使用for (item in items) 重新分配item = nil 时,为什么要/需要/关心设置item = nil
    • 项目可能不包含任何对象。
    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 2015-07-18
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多