cannyboy
cannyboy

Reputation: 24426

Is this a job for NSTimer? Looping interface changes

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?

Upvotes: 1

Views: 1256

Answers (1)

Peter N Lewis
Peter N Lewis

Reputation: 17811

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:)

Upvotes: 3

Related Questions