Re: cocoa newbie questions
Re: cocoa newbie questions
- Subject: Re: cocoa newbie questions
- From: Joe Muscara <email@hidden>
- Date: Mon, 5 Nov 2001 15:01:34 -0600
On Monday, November 5, 2001, at 12:18 PM, Lieven Dekeyser wrote:
I just started writing cocoa/obj-c-apps in, and it's been a wonderful
experience so far. I'm never going back to carbon/c++ :-)
Neither am I! Cocoa is fun; Carbon/C++ is tedious in my opinion.
But there are still some things unclear:
- can anyone explain me the whole autorelease/release/retain thing? And
how do the Cocoa classes use them? when do you need to send release to
an
object created by a cocoa class? for example:
NSArray * array = [NSArray arrayWithObject:@"foo"];
do you need to call [array release] at the end of the function? Or is
the
array automatically released?
For more general info about autorelease/release/retain, others have
provided good links at Stepwise and O'Reilly. Also check out chapter 6
in "Object Oriented Programming and the Objective-C Language." You
should have this book in /Developer/Documentation/Cocoa/ObjectiveC.
As far as the class methods that create an instance of that class (such
as the one you named), these instances are autoreleased. You can spot
these methods by the + in the documentation, and they almost always have
a name that includes the class name, like "arrayWithArray,"
"stringWithString," etc. There is also usually (always?) a parallel
"init..." method where you have to autorelease/release/retain yourself.
These are used like the following:
myArray = [[NSArray alloc] initWithArray:someArray];
The class method returns an autoreleased object, the above call does not.
myArray = [NSArray arrayWithArray:someArray]; // myArray will be
autoreleased unless you add any retains.
There are reasons to use each that you'll learn as you master
autorelease/retain/release.
Have fun!
Joe