开发者

Pausing iteration of a for loop to wait for user input

开发者 https://www.devze.com 2023-03-02 13:01 出处:网络
I wrote a for loop which is iterating through an array of objects. Now I am asking myself if it\'s possible to break the iteration of the loop until the user clicks on a button which calls a IBAction?

I wrote a for loop which is iterating through an array of objects. Now I am asking myself if it's possible to break the iteration of the loop until the user clicks on a button which calls a IBAction?

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

   // wait for action method called
   // user 开发者_如何学JAVAclicked action so go on
}


You can adapt the code to fit your case. It basically "unrolls" the loop into multiple messages. Start the sequence with [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's NSRunLoop concept expects you to complete processing pretty quickly. If you tie up the main thread by waiting for something, nothing else in your app can happen. The above code breaks the "wait" into multiple message sends, and keeps your app responsive.


ODRM algorithm works very well. I just changed this line :

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

with this :

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

As I had UI elements to be updated, it was better for we to force waiting to be in a background thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号