How many times do I release an allocated or retained object?

喜你入骨 提交于 2019-11-26 08:30:37

问题


I am making an iPhone game. I want to release all objects that have been allocated or retained. In the dealloc function I am releasing all such objects, but then I realized that sometimes I end up releasing objects when they have not been allocated yet. So I figured I need to check if its retainCount is greater than zero or not before I release it.

My question is:

Do I just check if the retainCount is greater than zero and then release it?

if([bg retainCount]!=0)
{
  [bg release];
}

or

Should I release it as many times as its retainCount

while([bg retainCount]!=0)
{
  [bg release];
}

Thanks for your help!


回答1:


Do not use -retainCount.

The absolute retain count of an object is meaningless.

You should call release exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).

See the Memory Management Guidelines for full details.




回答2:


Autorelease makes retainCount meaningless. Keep track of retains & whether you own an object. Study & remember these rules: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH



来源:https://stackoverflow.com/questions/3730804/how-many-times-do-i-release-an-allocated-or-retained-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!