I'm trying to maintain an internal array of all the instances of a given class. When one is naturally dealloc'd it should be removed from that static array.
However, dealloc
will never get called if [instances addObject:weakSelf]
is uncommented. When that is commented out, then dealloc
messages appear normally. How can this be achieved?
__weak MyClass *weakSelf; // A weak reference to myself
static NSMutableArray *instances;
- (instancetype)init {
self = [super init];
if (self) {
if (!instances) {
instances = [[NSMutableArray alloc]init];
}
weakSelf = self;
// Remember this instance
[instances addObject:weakSelf];
NSLog(@"Instances count: %lu", (unsigned long)instances.count);
}
return self;
}
- (void)dealloc {
// Remove this instance from the array
[instances removeObject:weakSelf];
NSLog(@"Instances count now: %lu", (unsigned long)instances.count);
}
+ (void)doSomething {
// enumerate the instances array and perform some action on each
}