How to nest a NSTimer within another one?
I would like to have an NSTimer which executes every 1 second and have another NSTimer which executes within that timer slightly less than 1 second.
Actually I am not sure what is the best way to do this, but I would like a random image to app开发者_开发百科ear every second and then disappear after after that second.
So I need some kind of stall or something which can pass the time and then execute the hide button again.
If I set the buttons hidden to TRUE and then set it to FALSE, this appearance time will be so short, how can I stall or make the second pass and then hide the image again?
Thanks in advance
You can try setting yourself into a constant cycle of showing and hiding the object after a specified interval until you interrupt it by using the performSelector:withObject:afterDelay:
method reciprocally in two counter-acting methods:
//On initialization, make a first call to the hide method
//to be executed after a delay
-(void) viewDidload {
[myObject setHidden:NO];
[self performSelector:@selector(hideObject) withObject:nil afterDelay:1.0];
}
//Whenever the hide gets called, hide, then make a call to the show method
//to be executed after a delay
-(void) hideObject {
[myObject setHidden:YES];
[self performSelector:@selector(showObject) withObject:nil afterDelay:1.0];
}
//Whenever the show gets called, show, then make a call to the hide method
//to be executed after a delay
-(void) showObject {
[myObject setHidden:NO];
[self performSelector:@selector(showObject) withObject:nil afterDelay:1.0];
}
You can interrupt the cycle by putting an if
statement which checks some end condition for you around the performSelector:withObject:afterDelay:
call .
I would recommend using NSTimer's initWithFireDate:interval:target:selector:userInfo:repeats:
. This will let you have the timer fire at a regular interval (if you set repeats
to YES
) and you can specify a fireDate
(the first time the timer is fired) to immediately for one loop and slightly later for the other. What's better about this method compared to performSelector
is that it can be easily terminated by sending invalidate
to the timers and will not be delayed by any blocking code you might have in either of your methods.
精彩评论