Re: dealloc and instance variables
Re: dealloc and instance variables
- Subject: Re: dealloc and instance variables
- From: Chris Hanson <email@hidden>
- Date: Sun, 23 Nov 2003 02:44:58 -0600
On Nov 23, 2003, at 12:16 AM, Graeme Mathieson wrote:
- (id)initWithString:(NSString *)aString
{
baz = [aString copy];
}
Of course you mean
- (id)initWithString:(NSString *)aString
{
if (self = [super init]) {
baz = [aString copy];
}
return self;
}
right? Objective-C isn't C++; there's no automatic calling of any
superclass initializer.
Do I need to also implement:
- (void)dealloc
{
[baz release];
}
Yes. But you need to implement it as:
- (void)dealloc
{
[baz release];
[super dealloc];
}
Objective-C isn't C++; there's no automatic calling of any superclass
dealloc method.
The purpose of a dealloc message is to deallocate all the memory
occupied by the receiver. NSObjects version of the method
deallocates the receivers instance variables, but doesnt follow any
variable that points to other memory.
This says it deallocates the *space occupied* by the instance variables
in the class. Not that it releases the objects the instance variables
point to.
It then goes on to show a dealloc method where the object sends a
release to its instance variables before passing the message onto its
superclass.
It's not sending a release to its instance variables. It's sending a
release to *the objects referenced by* its instance variables, and then
sending a dealloc to its superclass so it can do the same. Eventually,
in the topmost -dealloc method (in NSObject) the space occupied by your
object -- its instance variables, including those of all its
superclasses, along with any metadata like its isa pointer and
reference count -- is deallocated.
While I'm here, another quick question: Is it valid to send a message
to a nil object?
Yes. Doing so just returns nil/NULL. Note that this may not do the
right thing if you're expecting a return value that isn't a
pointer-sized value. This is well-documented.
-- Chris
--
Chris Hanson <email@hidden>
bDistributed.com, Inc.
Outsourcing Vendor Evaluation
Custom Mac OS X Development
Cocoa Developer Training
_______________________________________________
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.