简体   繁体   English

如何解决内存泄漏

[英]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. 如果您不使用ARC。

Whenever you return an object from method, Return an autoreleased object: 每当您从方法返回对象时,都将返回一个自动释放的对象:

return [dataViewController autorelease];

I'll suggest using ARC is a good option. 我建议使用ARC是一个不错的选择。 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. ARC是一种编译时功能,它将在您编译源代码时自动为您添加保留,释放调用。

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. 我认为可以肯定发问者使用的是手动内存管理而不是ARC,因为我不认为该代码会在ARC下泄漏。

Having said that, Midhun MP's answer is correct. 话虽如此,Midhun MP的答案是正确的。 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. Objective-C在方法上使用命名约定来确定其内存管理语义。 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). 例如,将期望一个名为newPerson的方法返回一个对象的拥有引用(该对象是保留计数为+1的对象)。 A method named person would be expected to return an autoreleased object, (that is an object without an owning reference). 期望一个名为person的方法返回一个自动释放的对象(即没有所有者引用的对象)。

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. 我喜欢用来记住约定的一种简单方法就是我从CARN规则中学到的知识。

  • C opy çOPY
  • A lloc 一个 LLOC
  • R etain [R Etain的
  • N ew ñEW

Any methods containing these words will be expected, in Cbjective-C, to return owning references to their returned objects. 在Cbjective-C中,任何包含这些单词的方法都应将拥有的引用返回给它们返回的对象。

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. 因此,总而言之,如果您打算从方法中返回一个拥有的对象,请修改其名称以包括上述单词之一,否则,请自动释放您返回的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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