Hi:
I need to make a for loop and between every loop wait 2 seconds and continue
for (int i = 0; i < [stories count]; i++) {
//my code
//sleep 2 seconds and continue
}
How can I do this?
Hi:
I need to make a for loop and between every loop wait 2 seconds and continue
for (int i = 0; i < [stories count]; i++) {
//my code
//sleep 2 seconds and continue
}
How can I do this?
The problem with this is that it will block the UI for 2 * [stories count]
seconds—certainly long enough for the user to notice that your app is not responding and appears to be hung. That's bad.
Use a timer instead, and keep the index (if you really do need the index) or an NSEnumerator ([stores objectEnumerator]
) in the timer's userInfo
. Implement your timer callback method to work on exactly one object. If you are using indexes, that method should also replace the index in userInfo
with the next one. Its final step will be to check whether you have run out of items, and if so, to call the method where you invalidate and release the timer (which you should also call from dealloc
).
For that matter, I question why you need to wait two seconds between operations. If you are waiting for something to happen, you should actually wait for that, and wait longer if necessary, instead of hard-coding a fixed two-second interval between operations.
Peter Hosey is right about blocking the UI thread, often called the main thread. But I think his solution is convoluted.
Simple solution 1: Call the method where the long blocking loop is on a background thread using:
[self performSelectorInBackground:@selector(longRunningMethod)
withObject:nil];
Simple solution 2: Add the method where the long blocking loop is to a NSOperationsQueue:
NSOperationQueue* oq = [[NSOperationQueue new] autorelease];
NSOperation* o = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(longRunningMethod)
object:nil]
[oq addOperation:o];
[o release];
Firing of selectors in the background is easier, almost too easy as they can drain resources if used to wildly.
Using NSOperationQueue needs a few lines of setup, but as a bonus it re-uses threads, and applies other optimizations to use less resources. As the name implies, it can also be used to queue operations. You can specify the maximum number of parallel operations, and different constraints.