How to create a timer the right way?

Posted by mystify on Stack Overflow See other posts from Stack Overflow or by mystify
Published on 2010-04-25T23:56:57Z Indexed on 2010/04/26 0:03 UTC
Read the original article Hit count: 119

Filed under:

I always have an class which needs to set up a timer for as long as the object is alive. Typically an UIView which does some animation.

Now the problem: If I strongly reference the NSTimer I create and invalidate and release the timer in -dealloc, the timer is never invalidated or released because -dealloc is never called, since the run loop maintains a strong reference to the target. So what can I do? If I cant hold a strong ref to the timer object, this is also bad because maybe I need a ref to it to be able to stop it. And a weak ref on a object is not good, because maybe i'm gonna access it when it's gone. So better have a retain on what I want to keep around.

How are you guys solving this? must the superview create the timer? is that better? or should i really just make a weak ref on it and keep in mind that the run loop holds a strong ref on my timer for me, as long as it's not invalidated?

© Stack Overflow or respective owner

Related posts about iphone