如何仅当保留计数达到 0 时才从 NSMutableArray 中删除对象?
我知道我不应该检查或使用保留计数,但我想知道是否有一种方法可以仅在其保留计数为 0 后才从 NSMutableArray 中删除对象。
基本上,我想将对象添加到数组,并让这些对象在其他窗口之间共享。当窗口使用它时,我希望保留计数增加 1。当不再使用它时,我希望它减少。但是,如果某些窗口仍在使用它,那么我希望它可供所有其他窗口使用。当所有窗口不再使用它时,我希望将其从数组中删除并完全释放。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于发布时自动从数组中删除,您可以使用关联对象,如 Dave DeLong 所描述:
如何将活动对象添加到NSMutableArray 并在它们发布时删除它们?
但你可能最好使用
NSCountedSet
,因为它完全实现了您想要的。它只是缺乏商品顺序。为了弥补项目顺序的不足,您可以使用额外的
NSMutableArray
来保持顺序,并在其中添加/删除项目与您的计数集同步。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.