Store an array of objects at the class level without the need to explicitly delete them

I have a class, say Chicken, and I want the class level method to list all currently existing Chickens. To do this, I save the class NSMutableArrayat the class level and add selfto this in the method init.

This is great, and my enumeration method just returns a pointer (not mutable) to this array.

The problem is that I can no longer free the chicken by deleting all pointers to it, since there is always a strong pointer in the array.

eg. If I do this ...

Chicken *chick = [[Chicken alloc] init];
// Do something with the chick
chick = nil;

The chicken lives because there is a strong pointer in the array. I may have a method -[Chicken kill]that removes it from the array, but that is not neat.

What is the neatest way?

+3
2

[NSHashTable weakObjectsHashTable] . . .

NSHashTable ( , NSDictionary), ARC __weak, - .

NSMutableDictionary *globalDict = [NSMutableDictionary dictionary];

// put object
id obj = [Foo new];
__weak id weakRef = obj;
globalDict[key] = [^() { return weakRef; } copy];

// read object
id (^block)(void) = globalDict[key];
id obj = block ? block() : nil;
if (!obj) {
    [globalDict removeObjectForKey:key];
}
+4

+ (NSValue *)valueWithNonretainedObject:(id)anObject . API, +arrayOfAllChickens, .

dealloc, .

+4

All Articles