Re: dealloc and instance variables
Re: dealloc and instance variables
- Subject: Re: dealloc and instance variables
- From: Chris Ridd <email@hidden>
- Date: Sun, 23 Nov 2003 07:00:05 +0000
On 23/11/03 6:16 am, Graeme Mathieson <email@hidden> wrote:
>
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:
Yes, you do.
[...]
>
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?
They're both correct, and consistent with each other. NSObject only sends
release to any instance variable *it knows about*, which doesn't include
anything in a subclass. That is why the Nutshell example sends dealloc to
super.
Your code may have still worked without the dealloc implementation, but it
will have been leaking memory.
>
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
Yes, but only if the return value is a pointer to an object, in which case
you're guaranteed to get nil back. Search ObjC.pdf for "message to nil" :-)
Cheers,
Chris
_______________________________________________
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.