Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to retain a scheduled NSTimer if you don't need to invalidate it?

I'm going back over some crufty code to tidy it up and I see I've been retaining NSTimers returned from scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: and storing them in a field - then releasing and nulling the field when it fires. In some cases I use the timer to send an invalidate message to it later - but in many cases not.

In more recent code I usually just schedule the timer and forget about it. I understand that the constructor method is autoreleasing and the timer is retained by the run loop while it is active - so I don't see any issue with this.

So, just to round out my understanding - is there any other reason I should be holding on to my timers, or is what I am doing now the accepted idiom?

This is all in the context of iPhone code, but I don't believe this is iPhone specific.

like image 319
philsquared Avatar asked Feb 01 '26 00:02

philsquared


2 Answers

I just let the run loop handle the retention, myself - it's the run loop that owns the timer and not me. If you see what I mean.

I'm answering my own question.

I was mostly asking the question because I'd been browsing through the class reference docs and this issue was not really made clear. I've since read the Timer Programming Topics: Using Timers article in the ADC and it covers it pretty well - especially the section on memory management at the end.

According to that what I am doing now (just scheduling, unless I need to be able to call invalidate, or isValid etc) is the right way.

like image 41
vamshi Avatar answered Feb 04 '26 02:02

vamshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!