创建 NsMutableData 期间发生泄漏
在创建 NSMutableData 期间我遇到了泄漏。我在connectionDidFinishLoading中释放了webData2...
webData2 = [[NSMutableData alloc]init];
所以我对此进行了测试:
NSMutableData *test =[[NSMutableData alloc]init];
webData2 = test;
[test release];
并且指令上有泄漏: NSMutableData *test =[[NSMutableData alloc]init];
我不明白!有人有主意吗?
谢谢你!
GT
During the creation of a NSMutableData i have a leak. I release webData2 in the connectionDidFinishLoading...
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];
I don't understand ! anyone have an idea ?
Thank you!
GT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不行的,
webData2
中的引用与test
相同,将被发布。NSMutableData* test = [[NSMutableData alloc] init]; // 测试指向对象B
webData2 = test; // test 和 webData2 都指向 A,没有任何东西指向 B
[test release]; // 对象 B 被释放,test 和 webData2 指向垃圾
所以问题出在第 3 行,您不再有对第 1 行分配的对象 B 的显式引用。
您需要释放
webData2< /code> 在为它分配新的对象指针之前。
正如 bbum 指出的那样,泄漏总是指对象分配的位置,而不是实际泄漏的位置。
如有疑问,请使用静态分析器(实际上总是不时运行静态分析器)。您将在 Xcode 的“构建”菜单下找到它,名称为“构建和分析”。它将在众多错误中找到大多数内存泄漏,并在页边空白处用蓝色箭头标记它们。展开箭头将显示从分配到最后一个引用丢失的泄漏的完整程序流程。
This will not work, the reference in
webData2
is the same astest
and will be released.webData2 = [[NSMutableData alloc]init]; // webData2 points to object A
NSMutableData* test = [[NSMutableData alloc] init]; // test points to object B
webData2 = test; // test and webData2 both points to A, nothing points to B
[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.
You need to release
webData2
before assigning it with a new object pointer.As bbum points out the leak is always referring to where the object is allocated, not where it is actually leaked.
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. 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.
你可以做的是:
那么 webData2 将不会与 test 一起发布...你必须稍后发布它。
what you can do is:
then webData2 will not get released together with test... you will have to release it later.