[[NSMutableData data]retain]什么时候释放?
我曾经在很多代码中看到 [[NSMutableData data] keep] 指令,但我不知道保留的对象何时被释放......你能帮我理解吗?
提前致谢,
斯蒂芬
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 ?
Thx in advance,
Stephane
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答是:在您释放它之前它不会被释放。您增加了保留计数,并且在此过程中,您承担了稍后释放它的责任。
您可能见过的一种情况是人们直接分配给 ivars;释放应该出现在
-dealloc
中——当包含的对象被销毁时——或者当 ivar 被重新分配时。但无论哪种情况,您都必须记住这样做,否则您的代码将会泄漏。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; the release should come in
-dealloc
—when the containing object is destroyed—or when the ivar is reassigned. But in either case, you must remember to do so, or your code will leak.事实并非如此。它泄漏了。
[NSMutableData data]
已经自动释放——它将在当前自动释放池结束时释放(即大多数情况下当前运行循环迭代结束时)。通过向其发送-retain
消息,您告诉它停留更长的时间,但如果没有相应的-release
消息,它的保留计数永远不会为0
因此永远不会被释放。It isn't. It leaks.
[NSMutableData data]
is already autoreleased--it will be released at the end of the current autorelease pool (i.e. 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 of0
and so will never be deallocated.[NSMutable data] 不会被释放,直到你在它的保留计数上加 1 时释放它。通过使用
[[NSMutable data]retain]
,您将为其保留计数加一,而通过释放它,您将为其保留计数减一。因此,当您使用完它(在 dealloc 方法中)时释放它。[NSMutable data] will not be released till you release it when you add 1 to it's retain count. 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. So when you are done using it (in the dealloc method) release it.