dealloc and instance variables
dealloc and instance variables
- Subject: dealloc and instance variables
- From: Graeme Mathieson <email@hidden>
- Date: Sun, 23 Nov 2003 06:16:26 +0000
If my object retains some other object in an instance variable, do I
have to explicitly write a -(void)dealloc method to release it when my
object is released? Take, for example:
@interface MyFooBar
{
NSString *baz;
}
- (id)initWithString:(NSString *)aString;
@end
@implementation MyFooBar
- (id)initWithString:(NSString *)aString
{
baz = [aString copy];
}
@end
Do I need to also implement:
- (void)dealloc
{
[baz release];
}
?
I started out by thinking that yes, obviously I'd have to release any
objects I allocate. That makes sense and my code did work OK in the
limited testing I've done. But then I read
http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/
4objc_runtime_overview/chapter_4_section_2.html which says:
Releasing Instance Variables
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.
So I interpret that to say "any of your instance variables which are
handled through the reference counting mechanism are automatically
dealt with, but if you malloc() bits and pieces you have to deal with
that yourself" and fix my code appropriately. Annoyingly, all my code
still works fine.
To confound matters, whilst reading 'Cocoa in a Nutshell' yesterday
afternoon, I read (from page 15 of my edition):
Deallocating Objects
[...]If the object has created or retained any other objects'
reference by its instance variables, it must implement this method and
perform the appropriate tasks to maintain integrity of the reference
counting system.
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.
So, which one is correct?
While I'm here, another quick question: Is it valid to send a message
to a nil object? My code currently doesn't make such an assumption, so
in a few cases I'm explicitly checking that a particular variable
points to an object rather than nil before sending a message. However,
my code would look far tidier if I was able to just send the message
anyway, so long as I was careful to reset instance variables to either
a valid object or nil.
--
Mail, MSN Messenger & Jabber: mathie [at] endless [dot] org [dot] uk
AIM: MathieEndless, Blog:
http://www.endless.org.uk/blog/
OpenPGP Fingerprint: 0F38 5000 999F 0644 76D6 968D A945 916E AD30 4A1A
_______________________________________________
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.