简体   繁体   English

什么时候发布[[NSMutableData数据]保留]?

[英]When does [[NSMutableData data] retain] is released?

I used to see [[NSMutableData data] retain] instruction in many codes but I don't know when the retained object is released...Can you help me understand ? 我曾经在许多代码中看到过[[NSMutableData data]保留]指令,但我不知道何时释放保留的对象...您能帮我理解吗?

Thx in advance, 提前谢谢

Stephane 斯蒂芬

The short answer is: it isn't released until you release it. 简短的答案是:直到您释放它,它才会被释放。 You've incremented the retain count and, in doing so, you've taken on the responsibility of releasing it later. 您已经增加了保留计数,并且这样做了,您承担了以后释放它的责任。

A situation you may have seen is one where people are assigning to ivars directly; 您可能已经看到的一种情况是人们直接分配给ivars。 the release should come in -dealloc —when the containing object is destroyed—or when the ivar is reassigned. 当包含对象被销毁时,或者在重新分配ivar时,发布应在-dealloc But in either case, you must remember to do so, or your code will leak. 但是无论哪种情况,您都必须记住这样做,否则您的代码将泄漏。

It isn't. 不是。 It leaks. 漏了

[NSMutableData data] is already autoreleased--it will be released at the end of the current autorelease pool (ie the end of the current run loop iteration in most cases.) By sending it the -retain message, you're telling it to hang around a bit longer, but without a corresponding -release message, it will never have a retain count of 0 and so will never be deallocated. [NSMutableData data]已经自动释放-它将在当前自动释放池的末尾(即在大多数情况下,当前运行循环迭代的末尾)释放。通过发送-retain消息,您可以告诉它保留更长的时间,但是没有相应的-release消息,它将永远不会有0的保留计数,因此永远不会被释放。

[NSMutable data] will not be released till you release it when you add 1 to it's retain count. 当您将[NSMutable数据]的保留计数加1时,它才被释放。 By using [[NSMutable data] retain] you are adding one to it's retain count and by releasing it you will be decreasing one from it's retain count. 通过使用[[NSMutable data] retain]您可以在保留数上添加一个,而释放它,则可以从保留数中减少一个。 So when you are done using it (in the dealloc method) release it. 因此,在使用完它(在dealloc方法中)后,请释放它。

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

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