Re: Maintaining a List of instances of a class
Re: Maintaining a List of instances of a class
- Subject: Re: Maintaining a List of instances of a class
- From: "Paolo Manna" <email@hidden>
- Date: Wed, 18 Jul 2007 14:32:11 +0100
how do I let a class maintain a list (MutableArray) of it's own instances?
In C++ I would do this just in the constructor.
You can try with - (id)init, the nearest thing you have to a
constructor: something like
static NSMutableArray *instanceList;
@implementation MyObject
- (id)init
{
if ([super init]) {
if (!instanceList)
instanceList = [[NSMutableArray alloc] initWithCapacity: 1];
[instanceList addObject: self];
// ... other initializations...
}
}
// ... rest of the code...
@end
However, please be aware that there's a catch: if you're not careful,
your object could end up to be around forever! The instance list will
retain the object even when every other has released it: that's why,
incidentally, you can't remove the object from the array during
dealloc - while it's in the array, dealloc isn't called at all! You
can possibly end up checking the retainCount every time you call
release, and removing from the array when it gets to 1 (that is, only
the array is keeping the object around).
Paolo
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden