Re: NSTimer retain and release questions
Re: NSTimer retain and release questions
- Subject: Re: NSTimer retain and release questions
- From: Ken Thomases <email@hidden>
- Date: Wed, 10 Sep 2008 13:58:33 -0500
On Sep 10, 2008, at 1:44 PM, Bill wrote:
On Sep 10, 2008, at 11:37 AM, Bill Bumgarner wrote:
On Sep 10, 2008, at 11:21 AM, Kyle wrote:
The documentation for this autoreleased method:
+ (NSTimer *)scheduledTimerWithTimeInterval:
(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector
userInfo:(id)userInfo repeats:(BOOL)repeats
states: "If repeats is NO, the timer will be invalidated after it
fires."
If I call this autoreleased method, and set repeats to YES, does
that imply I do not need to retain the object if I want to
invalidate it later? In other words, is this autoreleased method
autoreleased only when repeats is NO, otherwise it is not
autoreleased?
Just want to make sure I understand it correctly. Thanks in
advance!
If you receive an autoreleased object, you must retain it if you
want to keep it. Doesn't matter what the object is.
b.bum
That's what I thought also. But for NSTimer objects, it seems as if
the way to release them is to invalidate them. In the above
autoreleased method, if repeats is YES, the object is not invalided,
implying it is not autoreleased. If repeats is NO, then the object
is autoreleased.
Part of the reason I'm asking is because originally I used the above
method with a retain (and released later with the invalidate
method), and then ran my app with Leaks, and Leaks told me that the
timer was leaking. I removed the retain from my code, and Leaks
stopped reporting a leak.
So I'm not sure what is correct.
You are confusing your ownership of the object with the other possible
owners that may exist. You are also confusing invalidating and
releasing.
The timer object you get back from the +scheduledTimer... method is
not owned by you. That is, you are not responsible for releasing it
and must not (except to balance any retains you otherwise put on it).
That does not necessarily mean the object _will_ be deallocated if you
don't retain it. It just means it _may_ be deallocated. For example,
it may be owned by some other object(s). In the case of timers, the
documentation for -[NSRunLoop addTimer:forMode:] says that the run
loop object retains the timer object.
Sending -invalidate is not the same as releasing the object. For
timers, it is documented that the run loop object, whose ownership of
the timer is a separate issue from your ownership of it, will release
the timer object when you invalidate the timer.
Cheers,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden