关于dealloc/release: x = nil; 总是可以的吗? [x发布]; - 或者它会引起问题吗?
因为每次对具有不同对象的变量进行赋值都会增加其保留计数,并且在 dealloc 中,并不总是清楚变量被分配的频率,简单的 [maVar release] 可能不够。因此,使用 ALWAYS myVar = nil
将保留计数设置为零,并且后续的 [myVar release]
永远不会再次导致问题。 (实际上仍然需要吗?)
不这样做的唯一情况是,如果 myVar 被传递出去,那么我不能这样做,因为该值会被 myVar = nil
; 破坏。
我的想法正确吗?或者这种避免泄漏的方法会导致任何其他问题吗?
since every assignment to a variable with a different object increases its retain count and in the dealloc its not always clear how often a variable got assigned a simple [maVar release] might NOT BE SUFFICIENT. So using ALWAYS myVar = nil
sets the retain count to zero, and a subsequent [myVar release]
will never cause a problem again. (is it actually still required ?)
The only situation when not to do it this way is if myVar is passed OUT then I must not do this, since the value gets destroyed by myVar = nil
;
Is my thinking correct? Or could this way of avoiding leaks cause any other problems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的想法在很多方面都是不正确的。这些可能只是表面现象:
dealloc
。myVar = nil
不会影响保留计数。myVar = nil
仅销毁本地指针值,它不会销毁已传递出去的对象。myVar
为nil
时,调用[myVar release]
是安全的,但它没有用——它什么也不做。很明显,你对C指针和Objective-C内存管理的掌握有点欠缺。我建议在多次彻底重新阅读内存管理文档。
Your thinking is incorrect in quite a lot of ways. These are probably just scratching the surface:
dealloc
is called when the retain count reaches 0.myVar = nil
does not affect the retain count.myVar = nil
destroys only the local pointer value, it does not destroy an object that has been passed out.[myVar release]
whenmyVar
isnil
, but it isn't useful -- it does nothing.It is clear that your grasp of C pointers and Objective-C memory management is a bit lacking. I'd suggest doing some remedial C work before several thorough re-reads of the Memory Management docs.
请阅读有关 内存的 Apple 文档管理。
将指针分配给对象不会增加
retain
计数,只有调用retain
才会增加。名称中带有 Copy 或 Init 的函数应返回一个保留计数为 1 的对象,其他函数应返回自动释放的对象,这些对象将在主循环完成时被释放。将对象设置为 nil 不会修改保留计数,但会导致内存泄漏。此时对指针调用
release
基本上不会执行任何操作。如果您想有效地管理内存使用情况,您需要负责使用retain
、release
、autorelease
以及如何命名函数。Please read Apple's documentation on Memory Management.
Assigning a pointer to an object will not increment the
retain
count, only callingretain
does that. Functions with Copy or Init in the name should return an object with a retain count of 1, other functions should return autoreleased objects that will be dealloc'd when the main loop finishes.Setting an object to
nil
doesn't modify the retain count, but it will cause that memory to leak. Callingrelease
on the pointer at that point essentially does nothing. You need to be responsible about usingretain
,release
,autorelease
, and how you name your functions if you want to effectively manage your memory usage.