How to remove an object from NSMutableArray only when retain count reaches 0?

纵然是瞬间 提交于 2019-12-25 06:34:12

问题


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

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