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?
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.
retainCount
of 1
but the only remaining retain keeping it allocated might be part of an autorelease pool which will release and therefore deallocate it when the pool drains at the end of the current run loop.retainCount
of 10
but your proposed object pool might have the only retain outside an autorelease pool so by the end of the current run loop it will be back to 1
.retainCount
of 10
but they could all be retains from autorelease pools and it will still be deallocated when the pool(s) drain.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).