Re: Disposing NSArray
Re: Disposing NSArray
- Subject: Re: Disposing NSArray
- From: Greg Titus <email@hidden>
- Date: Thu, 31 May 2001 20:43:59 -0700
On Thursday, May 31, 2001, at 04:03 PM, Youngjin Kim wrote:
What's the differerence between two?
Both array1 and array2 are locally instantiated in a method.
-(void) doSomething {
NSArray* array1;
NSArray* array2;
array1 = [[NSArray arrayWithObjects:s1,s2,s3,s4,nil] autorelease];
array2 = [[[NSArray alloc] initWithObjects:s1,s2,s3,s4,nil]
autorelease];
...
}
I'm getting signal raised with array1. but array2 work fine.
The rules are: if you alloc, copy, or retain something, you also need to
(eventually) release or autorelease it. If you don't do any of those
three things, you don't need to do any memory management at all. (Not
only don't need to, if you try, it messes things up, as you are
noticing...)
So the difference is, with array1 you are not allocating it yourself --
the class method is doing it for you and returning an object which has
ALREADY been autoreleased. When you autorelease it again you are causing
an error when the objects are cleaned up by the autorelease pool because
it is an object which has 2 releases for only 1 retain.
With array2, you ARE allocating it yourself, so calling autorelease on
it is appropriate, and necessary to avoid a memory leak.
(The actual mechanism here is that when you call autorelease, a pointer
to the object is added to a list keep by an NSAutoreleasePool. When that
pool is deallocated, every object in the list gets a -release method.
Thus -autorelease is a delayed -release. With array1, the first time the
pool calls -release on it, the object sees that no one else is retaining
it (the retainCount is zero) so it deletes itself. Then the pool sees
that same object pointer in its list a second time, tries to call
-release on it, and your app blows up because you are calling a method
on something which is no longer a valid object.)
Hope this helps,
--Greg