0

我写了一个for循环,它遍历一个对象数组。现在我问自己是否有可能中断循环的迭代,直到用户单击调用 a 的按钮IBAction

for (int i = 0; i < [array count]; i++) {
   // do something with the object

   // wait for action method called
   // user clicked action so go on
}
4

2 回答 2

4

您可以调整代码以适合您的情况。它基本上将循环“展开”成多条消息。开始序列[self doItForIndex:[NSNumber numberWithInt:0]];

- (BOOL)canDoitForIndex:(NSNumber *)i {
    // return YES if you want to go ahead
    // (e.g. test a BOOL you set in response to the user tapping a button
}

- (void)waitForIndex:(NSNumber *)i {
    if ([self canDoItForIndex:i]) {
        // do anything to clean up for i
        // then repeat for i+1:
        [self doItForIndex:[NSNumber numberWithInt:[i intValue]+1]];
    } else {
        [self performSelector:_cmd withObject:i afterDelay:0.01f;
    }
}

- (void)doItForIndex:(NSNumber *)i {
    if ([i intValue] < lastIndex) {
        // do what you have to do
        [self waitForIndex:i];
    }
    // else you're done
}

Apple 的NSRunLoop概念希望您能够很快完成处理。如果您通过等待某些事情来占用主线程,那么您的应用程序中不会发生任何其他事情。上面的代码将“等待”分解为多个消息发送,并使您的应用程序保持响应。

于 2011-04-30T17:07:48.120 回答
1

ODRM 算法效果很好。我刚刚更改了这一行:

[self performSelector:_cmd withObject:i afterDelay:0.01f];

有了这个 :

   [NSThread sleepForTimeInterval:0.25];  
   [NSThread detachNewThreadSelector:_cmd toTarget:self withObject:i];

因为我有 UI 元素要更新,所以我们最好强制等待在后台线程中。

于 2012-03-11T17:51:03.477 回答