简体   繁体   English

在创建NsMutableData期间泄漏

[英]Leak during the creation of a NsMutableData

During the creation of a NSMutableData i have a leak. 在创建NSMutableData期间,我有一个泄漏。 I release webData2 in the connectionDidFinishLoading... 我在connectionDidFinishLoading中发布webData2 ...

webData2 = [[NSMutableData alloc]init];

So I have test this : 所以我测试了这个:

NSMutableData *test =[[NSMutableData alloc]init];
webData2 = test;
[test release];

and I have a leak on the instruction : NSMutableData *test =[[NSMutableData alloc]init]; 我的指令有泄漏: NSMutableData *test =[[NSMutableData alloc]init];

I don't understand ! 我不明白! anyone have an idea ? 有谁有想法?

Thank you! 谢谢!

GT GT

This will not work, the reference in webData2 is the same as test and will be released. 这是行不通的,在参考webData2相同test ,将被释放。

  1. webData2 = [[NSMutableData alloc]init]; // webData2 points to object A
  2. NSMutableData* test = [[NSMutableData alloc] init]; // test points to object B
  3. webData2 = test; // test and webData2 both points to A, nothing points to B
  4. [test release]; // object B is released, test and webData2 points to garbage

So the problem is at line 3, where you no longer have an explicit reference to object B allocated at line 1. 所以问题出在第3行,你不再明确地引用第1行分配的对象B.

You need to release webData2 before assigning it with a new object pointer. 您需要在使用新对象指针分配webData2之前释放它。

As bbum points out the leak is always referring to where the object is allocated, not where it is actually leaked. 正如bbum指出的那样,泄漏总是指对象的分配位置,而不是实际泄漏的位置。

When in doubt use the static analyzer (actually always run the static analyzer from time to time). 如有疑问,请使用静态分析仪(实际上总是经常运行静态分析仪)。 You will find it in Xcode under the Build menu as Build and Analyze . 您可以在Build菜单下的Xcode中找到它作为Build and Analyze It will among many errors find most memory leaks, and mark them with blue arrows in the margin. 它会在许多错误中发现大多数内存泄漏,并在边距中用蓝色箭头标记它们。 Expanding the arrows will show the complete program flow for the leak from the allocation to the last reference getting lost. 展开箭头将显示从分配到最后一个参考丢失的泄漏的完整程序流程。

what you can do is: 你能做的是:

NSMutableData *test =[[NSMutableData alloc]init];
webData2 = [test copy];
[test release];

then webData2 will not get released together with test... you will have to release it later. 然后webData2将不会与测试一起发布...您将不得不稍后发布它。

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

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