iosobjective-cswiftpoolnsautoreleasepool

Just how unreliable is -retainCount, exactly?


I'm looking to create an object pool that doesn't require the consumer to manually let go of the object. Instead, every time a new object is asked for, it checks all of the objects in the pool to see if their retain count is 1 (only owned by the pool). If it is, then it returns it.

How many hacks would be needed to get this general plan working?

Example : I know that some NSStrings that can't be released always have a retain count of -1, and that tagged pointers can't be deallocated (nor would I want them in an object pool). Would classes that aren't part of the basic set (NSString, NSArray, NSDate, and a few others), e.g. UIView, have fewer optimizations around retaining and thus be more reliable in their retain counts?


Solution

  • retainCount is reliable for the information it provides but also probably useless for the use you have described.

    retainCount tells you how many retains exist for an object (mostly, as you noted there are several exceptions for objects which cannot be deallocated). However it tells you nothing about who the owners of those retains are. In particular you cannot use it to determine if any of those existing retains are part of autorelease pools.

    Additionally from your question it's unclear why you think you need this behavior. You can usually return autoreleased objects to your consumer. The consumer should retain the object if they intend to reuse it however regardless of if they do so or not your pool could choose to retain and reuse the object (or not).