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: Tommy Nordgren <email@hidden>
- Date: Wed, 18 Jul 2007 15:56:05 +0200
On 18 jul 2007, at 15.32, Paolo Manna wrote:
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
It's better implementing this in Objective C++.
And declare:
static std::set<id> instanceList;
/* the id's will be sorted according to adress */
static NSMutableArray *instanceList;
@implementation MyObject
- (id)init
{
if ([super init]) {
/*delete if statement */
if (!instanceList)
instanceList = [[NSMutableArray alloc] initWithCapacity:
1];
instanceList.insert(self);
/* delete the next line */
[instanceList addObject: self];
// ... other initializations...
}
return self;
}
// ... rest of the code...
-(void) dealloc
{
.. /*release any object references - and then ..*/
instanceList.erase(self);
[super dealloc];
}
@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:
40comhem.se
This email sent to email@hidden
-------------------------------------
This sig is dedicated to the advancement of Nuclear Power
Tommy Nordgren
email@hidden
_______________________________________________
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