views:

186

answers:

6

I got a little stuck and I'm hoping someone can point me in the right direction. I have an NSMutableArray that stores a sequence. I created an enumerator so that a while loop can get the content of the array one by one.

Everything works fine however I want the methods to be called with a 10 second gap in between each call. Right now it plays all at once (or in very quick order). What should I look at to create a delay in between method calls?

Below is what I got so far. Thanks!

NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];
id element;

while(element = [enumerator nextObject])
{
 NSLog(element);

 int elementInt = [element intValue];
 [self.view showButton:elementInt];
}
+2  A: 

This is what NSTimer is for. Use NSTimer to get each element in the array sequentially.

Chris Hanson
+2  A: 

As an aside: you might want to take a look at Objective-C 2.0's Fast Enumeration

Abizern
Except that's kinda the opposite of what he wants. He wants to enumerate *really slowly*.
Kevin Ballard
Don't you know that it's an established military tradition - Hurry up and wait.
Abizern
+3  A: 

You almost certainly don't want to stick a "delay" in your loop, which will block the thread until it's over (and, unless your app is multi-threaded, block the entire thing). You could use multiple threads, but instead I'd probably split the loop out over repeated timed calls of another selector. Store the enumerator (or current index), and then look at NSObject's performSelector:awithObject:afterDelay:

So something like

[NSObject performSelector:@selector(some:selector:name:) withObject:objInstance afterDelay: 10]

where the selector will pickup the current enumerator, use it, advance it and schedule another call. Make sure you don't allow changes to the collection whilst this set of timed methods is executing.

Adam Wright
+1  A: 

If you end up passing your object enumerator around with a timer, know that you are not allowed to modify your array's contents until you are finished enumerating it.

Ashley Clark
A: 

So here was the solution that I came up with based on everyones input.

NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];

NSTimeInterval time = 5;

for (NSString *element in enumerator) {
 id elementId = element;

 time++;

 [self.view performSelector:@selector(showButton:) withObject:elementId afterDelay:time];
}

Thanks again for pointing me in the right direction everyone.

acreek
the time++ means that the selector will fire after 6, 7, 8, ... seconds
Abizern
Yeah I wanted a short delay between each method call.
acreek
+1  A: 

if gameSequenceArray is an array, then you don't need to use an enumerator:

NSTimeInterval time = 10;

for (id elementId in gameSequenceArray) {

    [self.view performSelector:@selector(showButton:) withObject:elementID afterDelay:time];
}

and then you declare showButton:

- (void)showButton:(id)anElement {
    ...
}
Abizern