tags:

views:

362

answers:

2

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.

+2  A: 

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.

Graham Lee
Yes, this isn't really a memory management question - although I included that in my wording in case there was something I'd misunderstood there. That said, if I was keeping a reference to it I'd retain it anyway - the runloop should release it when it fires.
Phil Nash
+1  A: 

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.

Phil Nash