Dan Morgan
Dan Morgan

Reputation: 2500

Do I have a leak with this statement?

The statement is:

//Pass the copy onto the child controller
self.childController.theFoodFacilityCopy = [self.theFoodFacility copy];

My property is set to:

@property (nonatomic, retain) FoodFacility *theFoodFacilityCopy;

The reason I think I have a leak is because copy retains the value and then my dot syntax property also retains the value. Doubly retained.

What is the correct way of writing the above statement?

Upvotes: 3

Views: 273

Answers (4)

Lounges
Lounges

Reputation: 4664

What is the advantage of doing this vs just setting the property to copy?

@property (nonatomic, copy) FoodFacility *theFoodFacilityCopy;

Upvotes: 0

Jens Ayton
Jens Ayton

Reputation: 14558

As mentioned by others, that is indeed a leak. If you expect to be using copies in this way, it’s likely your property should be declared copy instead and the synthesized accessor will do the work for you.

Upvotes: 6

hacken
hacken

Reputation: 2145

You are right. The cleanest way is something like

id temp = [self.theFoodFacitlity copy];
self.childController.theFoodFacilityCopy = temp;
[temp release]

You want to read the apple site on memory management a lot until these rules become second nature.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187074

yes, you do have a leak there.

SomeClass *someObj = [self.theFoodFacility copy];
self.childController.theFoodFacilityCopy = someObj;
[someObj release];

This mirrors the recommended approach for initializing an object too:

SomeClass *someObj = [[SomeClass alloc] init];
self.someProperty = someObj;
[someObj release];

In both cases the first line returns an objects with a retain count of 1, and you treat it identically after that.

Upvotes: 9

Related Questions