问题
I know I'm not supposed to check or use retainCount, but I'm trying to wonder if there's a way to have an object be removed from an NSMutableArray only after its retain count is 0.
Basically, I want to add objects to an array, and have those objects be shared among other windows. When a window uses it, I want the retain count to go up by 1. When it's no longer used, I want it to go down. But, if some window is still using it, then I want it to be available to all other windows. When all windows are no longer using it, then I want it to be removed form the array and released entirely.
Thanks!
回答1:
For the automatic removal from array on release you could use associated objects, as Dave DeLong described here:
How to add alive object to NSMutableArray and remove them when they're released?
But you'd probably be better off using an NSCountedSet, as it implements exactly what you're after. It just lacks item order.
To make up with the lack of item order you could use an additional NSMutableArray
to keep order and add/remove items to/from it in sync with your counted set.
来源:https://stackoverflow.com/questions/6403175/how-to-remove-an-object-from-nsmutablearray-only-when-retain-count-reaches-0