Can I send argument with @selector
in NSTimer
? If I want to release NSTimer
, are the following steps right in dealloc
?
[timer invalidate];
[timer release];
Can I send argument with @selector
in NSTimer
? If I want to release NSTimer
, are the following steps right in dealloc
?
[timer invalidate];
[timer release];
[timer release]
only needs to be called if you "own" the timer. From Apple's documentation:What does this mean?
If you
alloc
andinit
a timer, you must alsorelease
it, like so:Once the timer has been added to the run loop, there is no reason to keep a reference to it anymore, since the run loops owns it. In this case, as shown, you would
release
the timer as soon as you add it to the run loop, and then simplyinvalidate
it when you are finished. The final line (setting timer tonil
) is for safety. The call toinvalidate
will result in the timer being released (by the run loop), so it is unsafe to keep a reference that points to it. Setting the local reference tonil
keeps things kosher.If, however, you create a timer using one of the convenience methods like so:
You do not need to call
[timer release]
at all! The convenience method adds the timer to the run loop, which then owns it, so you do not need to perform any memory management on the returned timer object. You would simplyinvalidate
the timer when you no longer want to use it:Or, if the timer was not set to repeat, you would do absolutely nothing at all, since it would be released after its first invocation.
The two methods do different things. If you own a timer (you retained it, or alloced it, or copied it) then you should release it. If you scheduled it on a run loop, then you must invalidate it for the run loop to release it. If you did both things, then you must release and invalidate the timer (however usually having the run loop owning the timer is sufficient).
That is the correct way to deallocate a timer that might still be running (and you want to stop).
Always, release is the last thing you do. Once you release something there is no guarantee it is safe to dereference the object, which means it no longer safe to send it ANY message.