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

折月煮酒 提交于 2019-12-12 13:33:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!