Question

I have a class with a property defined in the .h file as:

@property (retain) NSString *fontName;

In the .m file I release the property:

-(void)dealloc {
    [super dealloc];
    [_fontName release];
}

Now I'm occasionally getting a EXC_BAD_ACCESS error on [_fontName release]. The occurrence is so rare that I'm not really sure how to debug it. Is is correct to release a @property (retain)? Or does [super dealloc] already do that?

Was it helpful?

Solution

Perform the super dealloc AFTER:

-(void)dealloc {
    [_fontName release];
    [super dealloc];
}

In short, kill your children before killing yourself.

OTHER TIPS

The more traditional approach is to simply release your instance variables and leave them pointing to the released (and potentially deallocated) object, like so:

- (void)dealloc
{

    [_fontName release];

    [super dealloc];
}

In this approach, each of the pointers will be pointing to a potentialy invalid object for a very short period of time — until the method returns — at which point the instance variable will disappear along with its owning object. In a single-threaded application (the pointer would have to be accessed by something triggered by code in either this object's implementation of dealloc or in the dealloc of one of its superclasses, there's very little chance that the instance variables will be used before they go away , which is probably what has led to the proclamations made by several that there's "no value in setting instance variables to nil" in dealloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top