should I release NSTimer if it has a repeats attribute equal to YES?
Sometimes I get confused about when not releasing an object. I have:
NSTimer *timer2;
timer2 = [NSTimer scheduledTimerWithTimeInterval:开发者_如何学JAVA (5)
target: self
selector: @selector(someMethod:)
userInfo: nil
repeats: YES];
and the method that get's executed every five seconds is:
-(void) someMethod:(NSTimer*)theTimer
{
NSLog(@"code got executed");
}
I have another method that places another nib file on my root view controller:
ViewControllerObjetivos *control = [ViewControllerObjetivos alloc];
[control initWithNibName:@"ViewControllerObjetivos" bundle:nil];
UINavigationController *navControl = [[UINavigationController alloc]
initWithRootViewController:control];
[self presentModalViewController:navControl animated:NO];
[navControl setNavigationBarHidden:YES];
[control release];
[navControl release];
when I call that last method a new nib file get's placed on the root view controller. And someMethod still gets called!
so I am confused if I should release the timer2 because I did not use the word init or alloc nor copy to initialize it. So what am I suppose to do? should I just stop it then call the last method that I showed? or maybe should I release the whole nib file since I am going to be working with a new one?
The correct way to stop a timer is calling its invalidate
method.
invalidate
Stops the receiver from ever firing again and requests its removal from its run loop.
In your case, you could store timer2
in an ivar of your class and then send it invalidate
at the proper moment, i.e., when you display the second nib (if I am not wrong). Not doing so will leave the timer running forever, as you witnessed.
If you set repeats
to NO
, the timer will be automatically invalidating after firing the first time:
repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
NSTimer's scheduledTimerWithTimeInterval returns an object that it owns, so you do not need to retain it. If you need to invalidate it(stop it) later, you should retain it yourself.
精彩评论