如何维护 class 的内部实例数组?

How to maintain an internal array of instances of a class?

我正在尝试维护给定 class 的所有实例的 内部 数组。当一个自然地被释放时,它应该从那个静态数组中删除。

但是,如果 [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
}

您应该创建一个 NSValue 非保留:

NSValue *value = [NSValue valueWithNonretainedObject:self];
[instances addObject:value];

参考:NSArray of weak references (__unsafe_unretained) to objects under ARC

或使用"a category that makes NSMutableArray optionally store weak references"

@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

参考:Non-retaining array for delegates