I have an NSTimer object that I need to repeatedly execute. The code that it calls is ultimately toggles a setting in my application through 4 various states. Each time the state changes, I want my interval to change on my timer. This loop should continue throughout the lifetime of the application.
As far as I can tell, you can not update the interval property on an NSTimer. I believe this means that I need to add code to create a new NSTimer object each time I toggle my state within my timer code. The following implementation is what I am thinking:
//Consider that in my containing class, there is an NSTimer property, named myTimer.
//My selector method, used by myTimer
-(void) updateState:(NSTimer *) timer
{
switch (AppState)
{
case state_1:
//Update current state to state_2
[self setMyTimer:[NSTimer scheduledTimerWithTimeInterval:30.0
target:self
selector:@selector(updateState:)
userInfo:nil repeats:NO];
break;
case state_2:
//Update current state to state_3
[self setMyTimer:[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(updateState:)
userInfo:nil repeats:NO];
break;
case state_3:
//Update current state to state_4
[self setMyTimer:[NSTimer scheduledTimerWithTimeInterval:30.0
target:self
selector:@selector(updateState:)
userInfo:nil repeats:NO];
break;
case state_4:
//Update current state back to state_1
[self setMyTimer:[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(updateState:)
userInfo:nil repeats:NO];
break;
}
}
Is this the most optimal solution or can the creation of all these timers cause any form trouble for my application as it continuously executes?
Also, I have ARC cut on within my project. In this case, will I still need to destroy the previous NSTimer objects?
Not as long as you’re managing the memory correctly. Using a synthesized setter will take care of this for you.
Not explicitly. When a non-repeating timer fires, it invalidates itself, and the run loop sends
release(because it had retained it). If you’ve got a claim on it, you’ll need to release it too, which you do using the setter.Since none of these timers are repeating, you could drop the ivar and instead use
performSelector:withObject:afterDelay:(By the way, I assume you’ve got
breaks in your real code. You definitely should if you don’t.)