Reputation: 239
Below code shows up a memory leak , when profiling.
ContentViewController *dataViewController;
dataViewController = [[ContentViewController alloc]initWithNibName:@"ContentViewController" bundle:nil];
dataViewController.DocumentPath = [self.modelArray objectAtIndex:index];
return dataViewController;
How can i solve this leak, Any idea please help me.
Upvotes: 0
Views: 147
Reputation: 58448
I feel it's safe to assume the questioner is using manual memory management as opposed to ARC as I don't believe this code would leak under ARC.
Having said that, Midhun MP's answer is correct. The returned object needs to be autoreleased to solve the immediate problem. But I wanted to add some information regarding why this is considered a leak by the profiling tools.
Objective-C uses naming conventions on methods to ascertain their memory management semantics. For example, a method named newPerson
would be expected to return an owning reference to an object (that is an object with a retain count of +1). A method named person
would be expected to return an autoreleased object, (that is an object without an owning reference).
In the first case, the caller of the method owns the object and is expected to release it when finished. The second case illustrates that the caller needn't worry about releasing the object (since it is not owned).
An easy way I like to use to remember the convention is what I learned as the CARN rule.
Any methods containing these words will be expected, in Cbjective-C, to return owning references to their returned objects.
So in conclusion, if you are intending to return an owned object from your method, amend its name to include one of the above words, or if not, autorelease your returned object.
Upvotes: 1
Reputation: 107131
If you are not using ARC.
Whenever you return an object from method, Return an autoreleased object:
return [dataViewController autorelease];
I'll suggest using ARC is a good option. Because it's much better than manual memory management. ARC is a compile time feature, it'll add retain, release calls for you automatically when you compile your source code.
Upvotes: 4