Do I have a leak with this statement?
//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?
Thanks
Dan
-
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.
Chuck : You could also just autorelease if you wanted to keep it a one-liner.Squeegy : In general, I try to avoid autorelease unless I really need it (Like returning an object from a method). Autoreleased objects can lead to hard to debug issues when things go wrong because the stack trace when it crashes does not intersect your code at all. I've been bitten by this before.Dan Morgan : Thanks Squeegy I have implemented this way of doing it into my program. Would this be ok too? self.childController.theFoodFacilityCopy = [self.theFoodFacility copy]; [self.childController.theFoodFacilityCopy release]; Would that reduce the retain count by 1? or not..Squeegy : Yes that would work, but it strikes me as very very bad form. Release what you own is the mantra. Your code finds an object that something else owns and releases it. It's just a bad idea that may lead to some bizarre debugging later on.Brent Royal-Gordon : Dan Morgan: That will work in this case, but if you ever turn theFoodFacilityCopy into a (copy) property instead of a (retain) one, that would cause the a leak *and* an early release. Good luck fixing that one! -
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.
-
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.
Squeegy : This is an excellent point too. Making the property use copy is by far the easiest way if this is a common operation for you. -
What is the advantage of doing this vs just setting the property to copy?
@property (nonatomic, copy) FoodFacility *theFoodFacilityCopy;Squeegy : If this is always how you assign the object, then you should do this, yes. But maybe this is a special case.
0 comments:
Post a Comment