calling [myString release] does NOT decrement [myString retainCount]

懵懂的女人 提交于 2019-11-29 15:54:01
mipadi

DON'T RELY ON RETAINCOUNT!

To humans, it's not an accurate measure of object ownership. You don't know what's calling retain and release behind the scenes in a framework.

Memory management in Cocoa is simple:

  1. If you alloc/init or copy an object, make sure you call release on it at some point.
  2. If you want to keep an object around, call retain -- but make sure to call release at some point, too.

Your third NSLog probably calls retainCount on a deallocated object.

The fact, that you see a value of 1 can have three reasons:

  1. There's some other object at the same address now, that has a retain count of one.
  2. (more likely) The deallocated object is still there. It responds to the message by returning the retain count, which would be one because it never was decremented to zero (no need to do that ever, since a deallocated object does not need a valid retain count).
  3. The object is still there and has some custom memory management, preventing retainCount from being decremented.

Edit:

To check deallocation of objects (if you want to be sure), you could always override dealloc and set a breakpoint or put a log message there.

This might help. From the docs about retainCount:

Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”. To diagnose memory management problems, use a suitable tool:

• The LLVM/Clang Static analyzer can typically find memory management problems even before you run your program.

• The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction.

• Shark (see Shark User Guide) also profiles memory allocations (amongst numerous other aspects of your program).

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