【发布时间】:2015-10-11 05:00:10
【问题描述】:
我正在尝试维护给定类的所有实例的 internal 数组。当一个自然地被释放时,它应该从那个静态数组中删除。
但是,如果未注释 [instances addObject:weakSelf],则永远不会调用 dealloc。当它被注释掉时,dealloc 消息会正常显示。如何实现?
__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
}
【问题讨论】:
标签: ios objective-c arrays static instances