Overriding dealloc with only NSLog


#1

On page 161 (ibooks edition), at the end of “Pointer Variables and Object Ownership”, we override dealloc like this:

-(void)dealloc { NSLog(@"Destroyed: %@", self); }

Since this overriden method prints to the console, but doesn’t do anything else, like actually actually deallocing something, wouldn’t that mean that in this example, the objects don’t get deallocated?

Thanks


#2

ARC takes care of all this stuff for you behind the scenes. It essentially adds the necessary code for cleaning up the objects.


#3

Even with ARC, the dealloc method is still useful; it can be used to release any resources not managed by ARC.


#4

So in practice the dealloc method does nothing?

i.e. It looks like this?

[code]

-(void)dealloc
{

}[/code]


#5

You can use it to release a malloced buffer, for instance:

-(void)dealloc
{
    free (_buffer);  // buffer was allocated with malloc.
}

#6

[quote=“Flyer28”]So in practice the dealloc method does nothing?

i.e. It looks like this?

[code]

-(void)dealloc
{

}[/code][/quote]

I’m somewhat of a newbie at this, but I believe method in the book deallocates the array items and the NSLog statement just adds in a print statement so you can see it happen in the output. If that’s not the case, hopefully someone will correct me.


#7

[quote=“Flyer28”]So in practice the dealloc method does nothing?

i.e. It looks like this?

[code]

-(void)dealloc
{

}[/code][/quote]

Before ARC, we would need to release our ownership of our variables in dealloc. The implementation would look like:

- (void)dealloc
{
    [_myVariable release];
    [_myOtherVariable release];

    [super dealloc];
}

Calling dealloc on NSObject (via the super call) would actually free up the memory on the heap that the object was taking up.

Under ARC, the system takes care of the releases and deallocs for us. So although when we override dealloc, we leave the implementation “blank”, at compile time, a [super dealloc]; line is added at the end. You can go ahead and try to add that super call yourself; you’ll see the compiler complain to you that “explicit calls to dealloc are not allowed under ARC,” or something to that extent.

Let me know if that helps!