0

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
}
Chan
  • 269
  • 1
  • 13

1 Answers1

0

You should create a NSValue nonretain:

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

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

Or using "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

Ref: Non-retaining array for delegates

Community
  • 1
  • 1
tuledev
  • 10,177
  • 4
  • 29
  • 49
  • Your ref lead me in the right direction (http://stackoverflow.com/a/4692229/4755085), so I ended up making a category on NSMutableArray that works well. Thanks. – Chan Oct 11 '15 at 06:18
  • Why not use NSPointerArray? – Willeke Oct 11 '15 at 12:47