0

So in the following example, is it possible to cast the parameter in some way, to make it weak or something ?

-(void)addObject:(NSObject *)object {
    [self.collection addObject:object];
}

By doing this, you would surely need to inspect each object you pull of the 'self.collection', to check to see if it is a dangling pointer, right ?

1 Answers1

3

I don't know is that answer to your question but there is an class call NSHashTable that can hold weak references to its members. You should have a look on it. You initialise it withe the option:

NSHashTable *hashTable = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];

The other options are:

  • NSHashTableStrongMemory
  • NSHashTableCopyIn
  • NSHashTableObjectPointerPersonality

And you use it in very similar way than NSArray but it's general purpose analogue of NSSet so maybe it's not good for you if you want to store non unique objects:

[hashTable addObject:@"myObj1"];
[hashTable addObject:@"myObj2"];
[hashTable removeObject:@"myObj2"];

I don't think you can stop weak reference with NSArray but the other option would be to wrap an object in value and stored the values instead:

NSValue *val = [NSValue valueWithNonretainedObject:@"myObj1"];
[array addObject:val];
Greg
  • 25,317
  • 6
  • 53
  • 62
  • `NSHashTable` doesn't maintain order like `NSArray`. Use `NSPointerArray` instead of `NSHashTable`. – rmaddy Nov 05 '15 at 17:30