Exegesis
Exegesis

Reputation: 1088

Objc Object Dealloc Memory Management

If I have an object called Catalog that has a (nonatomic, retain) attrib called "title". I do "[attrib release];" in the dealloc method of Catalog:

-(void)dealloc {
    [title release], title = nil;
    [super dealloc];
}

Later I do "Catalog *c = [Catalog new];".

Compare 1:

dto.title = [[NSString alloc] initWithFormat:@"...", ...];

and 2:

dto.title = [NSString stringWithFormat:@"...",...];

It is common sense to release all attribs of an object in the dealloc method, but what if I pass along an accessor method (that already has an autorelease)? Should I release or not release the accessor'd attribute in dealloc then?

Upvotes: 0

Views: 245

Answers (2)

Caleb
Caleb

Reputation: 125037

Your setter for title retains the string, so it needs to be released in -dealloc. Your first case is just wrong... you're calling +alloc followed by +stringWithFormat:. I suspect you mean -initWithFormat:. Also, you need to release the string there because you're alloc'ing it. It's ugly and unreliable to call -release on a property, so it's common to use a temporary variable for this sort of thing:

NSString *string = [[NSString alloc] initWithFormat:...];
dto.title = string;
[string release];

Upvotes: 4

Rayfleck
Rayfleck

Reputation: 12106

If the accessor already has an autorelease, then don't release it again in dealloc. The new+copy+alloc count must match the release+autorelease count.

Upvotes: 1

Related Questions