views:

500

answers:

1

A button on my inferface, when held down, will perform a series of changes on other parts of my interface.

For instance, for one second some text will turn blue, then a UImageView will change its image for two secs ...etc etc...

This series of changes will keep looping thru the same steps as long as the button is held down.

I've never used NSTimer before, but would this be the way to go?

+2  A: 

You don't need an NSTimer for this, you can simply use performSelector:withObject:afterDelay: sequencing from one method to the next until you start again. Start the process when the button is held down, and call cancelPreviousPerformRequestsWithTarget:selector:object: when the button is released. Something like:

- (void) step1
{
    // turn blue
    [self performSelector:@selector(step2) withObject:nil afterDelay:1.0];
}

- (void) step2
{
    // change image
    [self performSelector:@selector(step3) withObject:nil afterDelay:2.0];
}

- (void) step3
{
    // turn red
    [self performSelector:@selector(step1) withObject:nil afterDelay:3.0];
}

- (void) stopSteps
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(step1) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(step2) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(step3) object:nil];
}

You could remember the currently executing "performSelector" selector and only cancel that one, but its hardly worth remembering it.

Alternatively, you could use an NSTimer and a state machine, but for what you describe, the above is probably easier - it depends on how consistent your sequence is and whether it is easier to specify your sequence as a set of steps like the above, or a set of data (in which case, use a state machine of some sort, with either an NSTimer or performSelector:withObject:afterDelay:)

Peter N Lewis
Thanks, that works. For future reference, I'm storing the delay times in an array, with several objects created like this:NSNumber *one = [NSNumber numberWithDouble:0.30];NSNumber *two = [NSNumber numberWithDouble:0.50];..etc.. I had to convert each object in the array to double, the NSTimerInterval, like so: double dubNum = [[array objectAtIndex:0] doubleValue]; NSTimeInterval dubNumTimer = dubNum; ... and then used afterDelay:dubNumTimer
cannyboy
^ the NSTimerInterval = then NSTimerInterval
cannyboy