Objective-C 中的实例数组
我需要存储特定类的实例数组。然后我可以从任何地方的类方法访问它。 (有点像很多单例)
起初我以为只有一个静态 NSMutableArray 并在 init
中将 self
添加到数组中,并在 dealloc
中添加将其从数组中删除。但由于 NSArray 保留其对象,因此永远不会到达 dealloc。
我希望在runtime.h之类的东西中有一个函数来获取类的所有实例,就像你可以获得所有类的列表一样。
那么我怎样才能跟踪内存中特定对象的所有实例呢?
I need to store an array of instances of a specific class. Which I can then access from a class method anywhere. (kind of like lots of singletons)
At first I thought to just have a static NSMutableArray and in init
add self
to the array and in dealloc
remove it from the array. But because NSArrays retain their objects, dealloc will never be reached.
I was hoping there would be a function in something like runtime.h, to get all instances of a class, just as you can get a list of all classes.
So how can I keep track of all instances of a specific that are in memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你考虑过
NSObject * array[3];
吗?Did you consider
NSObject * array[3];
?创建一个简单的非保留数组:
to create a trivial non-retaining array:
当您的应用程序终止时,是否仍有大量单例对象尚未释放,这并不重要。由于您的数组是单例,因此它不会消失是没有问题的。
唯一的问题是数组中的对象。如果将它们添加到
-init
中的数组中,则无法从-dealloc
中的数组中删除它们,因为-dealloc
永远不会叫。如果您只想保留对某种类型的所有活动对象的引用,您可以使用 NSPointerArray 类似于数组但不保留其元素。It really doesn't matter if, when your application terminates, there are still lots of singleton objects which haven't been deallocated. Since your array is a singleton, there's no problem with it not going away.
The only problem is whith the objects in the array. If you add them to the array in
-init
, you can't remove them from the array in-dealloc
because-dealloc
will never be called. If you just want to keep a reference to all of the live objects of a certain type, you could use an NSPointerArray which is like an array but doesn't retain its elements.