【问题标题】:Early Exit from Fast Enumerate Loop?提前退出快速枚举循环?
【发布时间】:2013-07-12 18:00:02
【问题描述】:

使用快速枚举时,有没有办法提前退出,即在遍历数组中的每个元素之前?

    for (element in myArray)
    {
        //is there a way to exit before running through every element in myArray?
    }

【问题讨论】:

    标签: objective-c fast-enumeration


    【解决方案1】:

    break; 将退出任何forwhiledo 循环。

    例如:

    for (element in myArray)
    {
         if (someExitCondition)
         {
             break; /* leave now */
         }
    }
    

    阅读:

    http://msdn.microsoft.com/en-us/library/wt88dxx6(v=vs.80).aspx

    【讨论】:

      【解决方案2】:

      更好的方法是使用块

      [dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
      stop = YES // To break the loop }];
      

      【讨论】:

      • 这种方法有什么优势?
      • 在原始帖子中,他们已经在使用标准 for 循环,所以我认为没有理由在不需要时将其更改为使用块。
      • 我不是说他/她应该使用它,但根据苹果 enumerateKeysAndObjectsUsingBlock 比常规 for 循环和快速枚举更快。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      相关资源
      最近更新 更多