Sobes.tech
Junior — Middle

Can you explain what NSHashTable is and how it is used?

sobes.tech AI

Answer from AI

NSHashTable is a collection in iOS (Objective-C/Swift), similar to NSMutableSet, but with a more flexible object storage policy. Unlike regular sets, NSHashTable can store objects with different ownership options: strong, weak, or no retention (weak, strong, or no retention).

This is useful when you need to avoid cyclic references or store objects without increasing the reference count, such as delegates or observers.

Example of using NSHashTable with weak references:

NSHashTable *weakTable = [NSHashTable weakObjectsHashTable];

NSObject *obj = [[NSObject alloc] init];
[weakTable addObject:obj];

// obj will be automatically removed from the table when there are no strong references to it

Thus, NSHashTable helps manage memory and references in collections where a regular NSMutableSet is not suitable.