【问题标题】:Objective-C start loop from the beginningObjective-C 从头开始​​循环
【发布时间】:2015-05-17 10:27:04
【问题描述】:

我有一个与循环和迭代有关的问题

我有一个情况:

for (Item *item in items)
{
    if (condition)
    {
        iterateAgain;
    }
}

Objective-C 提供的continue 操作符只会从一个新的迭代开始。运算符break 会跳出整个循环。

实现这一点的最佳方法是什么?

【问题讨论】:

  • 你为什么一直在编辑问题,从而使解决方案与众不同?
  • 对不起,那是我的错。不再编辑!
  • 我的解决方案假设itemsNSSet,这是第一次编辑。不过原理应该很清楚。

标签: objective-c loops for-loop foreach


【解决方案1】:

您不能使用 快速枚举,这似乎是您正在使用的;改用基于索引的循环:

NSSet *items = [Model items];
NSArray *itemsArray = [items allObjects];
for (NSInteger index = 0; index < [itemsArray count]; index++) {
    Item *item = itemsArray[index];
    // ...
    if (condition) {
        index = 0;
        // Possibly use 'continue' here, depending what else is in the loop
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多