Re: Leaking Memory
Re: Leaking Memory
- Subject: Re: Leaking Memory
- From: Mike Shields <email@hidden>
- Date: Mon, 20 Jan 2003 20:33:01 -0700
On Monday, January 20, 2003, at 05:19 PM, David Cairns wrote:
Well, these explanations are close, but not quite correct.
alloc -- allocates memory for an object
init -- initializes the data members of an object
release -- deallocates an object _right away_
Nope. It just decrements the retain count. IIF the retain count == 0 as
a result of the release call is the object dealocated.
autorelease -- deallocates an object when you don't need it anymore
(generally at the end of whatever method the autorelease is declared)
Yes, it releases the object later. When it does that is governed by the
NSAutoreleasePool the object is placed in by the -autorelease message.
The normal case is at the end of the event loop. But if you have
created your own autorelease pool, it's when that pool is finally
released.
[snipped the rest]
I've always found the memory management in Cocoa to be quite easy. I
think it's cause I've always followed the rules of Cocoa.
1) Any object obtained from a method with alloc/init/copy in the name
must be released by the caller.
Example : foo = [[NSFoo alloc] init]; [foo release];
foo = [bar copy]; [foo release];
2) Any object obtained from any other method is assumed to be
autoreleased and does not need to be released by the caller. But if the
caller wants to keep these object around past the current code
block/method/function, then a retain must be placed on the object.
Example : foo = [NSString stringWithFormat:@"This is a test"];
foo = [NSArray objectAtIndex:1];
If I assume these rules are valid for all Cocoa methods (and they are)
and follow them in my own methods to the letter, I've never had a
problem with memory management.
Mike
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.