Question

I'm new to Objective-C, so please bear with me. I need to create an array (or a set) of name=value pairs with one condition that names can repeat in the set (thus I can't use NSMutableDictionary.) I found out that NSMutableSet seems to be what I need, but my dilemma now is how to add two NSString objects into it?

Was it helpful?

Solution

You probably cannot use NSMutableSet either because sets do uniquing by hash. If you have two objects that have the same hash (like two NSStrings that have the same characters) then you will end up with just one string in the set as well.

You probably would want to use an NSMutableArray where you put an object that has a key property and a value property that points to the actual object. Alternatively you can have your values in the NSArray by themselves and if you are looking for a certain one you can walk through the array and get the objects that have the matching key. Or more elegantly filter the array by key using an NSPredicate.

For how to filter arrays with predicates see here: http://www.cocoanetics.com/2010/03/filtering-fun-with-predicates/

OTHER TIPS

You can still use a dictionary, but for the values use an array or a set. This way you can map the same key to multiple different values.

I wouldn't use a set, I think you should still use an NSMutableDictionary as at the root of your problem is a key-based lookup.

What you want to do is have an NSMutableArray as the 'value' and the name as the key. If the key has not yet been used, create an NSMutableArray inside the dictionary with the first value. If the key has already been used, just add the value to the NSMutableArray already inside the dictionary.

Here is some sample code for a "setValueForKey" method:

NSMutableDictionary *dictionary = /* Some mutable dictionary stored as an instance variable or similar */
NSString *keyToAdd; id valueToAdd;

NSMutableArray *arrayForKey = [dictionary objectForKey:keyToAdd];

if (arrayForKey != nil) { // if the array has been created before earlier in the program
    [arrayForKey addObject:valueToAdd]; // then just add the value directly to the array inside the dictionary
} else { // otherwise create the mutable array using the key
    NSMutableArray *newMutableArray = [[NSMutableArray alloc] initWithCapacity:0];

    [dictionary setObject:newMutableArray forKey:keyToAdd];

    [newMutableArray addObject:valueToAdd];
}

To implement this logic, technically you could create a subclass of NSDictionary, but I think a custom wrapper object would be semantically better.

You should go for a NSDictionary because it is hash mapped and faster. You can create a custom class having a property of type array. store all values there and use that object as value and put a key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top