Just wanted to share this little tidbit. A little code someone wrote to make a category of NSMutableArray so that a weakly referenced array can be created!
NSMutableArray with weak references
For Mac, this is achievable simply using NSHashTable. But that class is not available for iOS.
Why would you want a weakly reference array? There are lots of reasons. In my case, I wanted to maintain a static reference array to all instances of a particular class
The code looks something like this:
#import "NSMutableArray.h"
@implementation MyClass
static NSMutableArray *allObjects;
+ (void) doSomething
//----------------------------------------------------------------------
{
int i=0,count=allObjects.count;
MyClass *obj;
for(; i<count; i++)
{
obj = [allObjects objectAtIndex:i];
[obj doSomething];
}
}
- (id) init
//----------------------------------------------------------------------
{
if((self = [super init]) != nil)
{
if(!allObjects)
allObjects = [[NSMutableArray mutableArrayUsingWeakReferences] retain];
[allObjects addObject:self];
}
return self;
}
- (void) dealloc
//----------------------------------------------------------------------
{
[allWindows removeObject:self];
[super dealloc];
}
- (void) doSomething
//----------------------------------------------------------------------
{
}
If the allObjects array were strongly referenced, then the dealloc method would never get called. You would need some kind of custom method for cleaning up the object since the allObjects array would always hold the last retain.
Since the array is weakly referenced, it holds no retains on the objects, and everything else works as expected.