简体   繁体   中英

How to solve a memory leak

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.

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.

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.

  • C opy
  • A lloc
  • R etain
  • N ew

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM