Synchronization cycle results

I am a bit stuck and I am hoping someone can point me in the right direction. I have an NSMutableArray that stores a sequence. I created an enumerator so that the while loop can get the contents of the array one by one.

Everything works fine, but I want the methods to be called with an interval of 10 seconds between each call. Now he plays immediately (or very quickly). What should I look at to create a delay between method calls?

Below is what I got so far. Thank!

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

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

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

      

+1


source to share


6 answers


You almost certainly don't want to stick to a "delay" in your loop that will block the thread until it finishes (and, if your application is not multithreaded, block the whole thing). You can use multiple threads, but instead, I would probably split the loop into repeated calls with another selector queue. Save the enumerator (or the current index) and then look at the NSObject performSelector: awithObject: afterDelay:

So something like



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

      

where the selector will load the current counter, use it, promote and assign another call. Make sure you do not allow changes to the collection while this set of temporary methods is running.

+3


source


This requires an NSTimer. Use NSTimer to get each element in the array sequentially.



+2


source


As an aside: you can take a look at Objective-C 2.0 Fast Enumeration

+2


source


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 {
    ...
}

      

+2


source


If you end up passing the object counter with a timer, be aware that you are not allowed to modify the contents of the array until you have finished enumerating it.

+1


source


So, here is the solution I came up with based on each 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.

0


source







All Articles