NSHashTable retaining weak reference

Viewed 1247

So, apple's documentation for [NSHashTable weakObjectsHashTable] states:

Returns a new hash table for storing weak references to its contents.

So, when I run the following code...

NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];
ABC *object = [[ABC alloc] init];
[hashTable addObject:object];
NSLog(@"%@", [hashTable anyObject]);
object = nil;
NSLog(@"%@", [hashTable anyObject]);

The output is:

2017-09-18 12:57:02.801 Test2[6912:640614] <ABC: 0x608000014eb0>
2017-09-18 12:57:02.801 Test2[6912:640614] <ABC: 0x608000014eb0>
2017-09-18 12:57:02.803 Test2[6912:640614] dealloc // (dealloc of ABC)

It looks like calling NSLog(@"%@", [hashTable anyObject]); is retaining the object.

If I call,

NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];
ABC *object = [[ABC alloc] init];
[hashTable addObject:object];
//NSLog(@"%@", [hashTable anyObject]);
object = nil;
NSLog(@"%@", [hashTable anyObject]);

The ouput is as expected:

2017-09-18 13:00:23.949 Test2[6936:645459] dealloc
2017-09-18 13:00:23.949 Test2[6936:645459] (null)

Can someone tell me where my misunderstanding is?

1 Answers
Related