我试图维护给定类的所有实例的内部数组。当一个人自然被释放时,它应该从那个静态数组中移除。
但是,如果取消注释dealloc
,则永远不会调用[instances addObject:weakSelf]
。当注释掉时,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
}
答案 0 :(得分:0)
您应该创建一个NSValue
nonretain:
NSValue *value = [NSValue valueWithNonretainedObject:self];
[instances addObject:value];
参考:NSArray of weak references (__unsafe_unretained) to objects under ARC
或使用"使NSMutableArray可选择存储弱引用的类别"
@implementation NSMutableArray (WeakReferences)
+ (id)mutableArrayUsingWeakReferences {
return [self mutableArrayUsingWeakReferencesWithCapacity:0];
}
+ (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity {
CFArrayCallBacks callbacks = {0, NULL, NULL, CFCopyDescription, CFEqual};
// We create a weak reference array
return (id)(CFArrayCreateMutable(0, capacity, &callbacks));
}
@end