Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa class to reference many entries by a single key

I need a Cocoa data structure to keep something like a list of locations of a set of insects in a field over time. Clearly an NSDictionary has to have unique keys, so I couldn't use the insect as a key and MKUserlocation as the object.

Is there any other class besides NSArray where one does not have to step through, if/else-ing at each index?

There seems to be such a thing as NSList discussed in various places but nothing in the Apple docs.

I also saw a reference to NSIndexSet one uses in conjunction to an NSArray, but again reading the Apple docs suggests it's not useful to me.

like image 875
aremvee Avatar asked Dec 12 '25 17:12

aremvee


1 Answers

Since Cocoa framework does not offer a multimap container, you could implement your own by creating an NSMutableDictionary, and populating it with NSMutableArray objects.

NSMutableDictionary locByInsect = [NSMutableDictionary dictionary];

// Adding a location for an insect:

MyInsect *insect = ... // Don't forget to provide hash code and equality checks
MyLocation *location = ...
NSMutableDictionary *insectLocations = locByInsect[insect];
if (insectLocations == nil) {
    insectLocations = [NSMutableArray array];
    locByInsect[insect] = insectLocations;
}
[insectLocations addObject:location];

// Retrieving all locations for an insect
for (MyLocation *loc in locByInsect[insect]) {
    NSLog(@"Saw %@ at %@", insect, loc);
}
like image 67
Sergey Kalinichenko Avatar answered Dec 16 '25 02:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!