问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/603044/is-there-any-reason-to-retain-a-scheduled-nstimer-if-you-dont-need-to-invalidat