I tried to lookup for this issue but with no luck, I want to build a function that creates a "Immutable Dictionary" of Keys and Objects where the object is also an Immutable Array.
What I will pass to this function is an array of objects I created, each object has a key property that I want to use to group the objects in the dictionary.
I came up with this and I tested it and it works but I want to see if there is a better/safer way to do this.
I do use ARC and I want to make sure every thing is immutable when i return from the function.
- (NSDictionary* )testFunction:(NSArray *)arrayOfObjects
{
NSMutableDictionary *tmpMutableDic = [[NSMutableDictionary alloc] init];
for(MyCustomObject *obj in arrayOfObjects)
{
if ([tmpMutableDic objectForKey:obj.key] == nil)
{
// First time we get this key. add key/value paid where the value is immutable array
[tmpMutableDic setObject:[NSArray arrayWithObject:obj] forKey:obj.key];
}
else
{
// We got this key before so, build a Mutable array from the existing immutable array and add the object then, convert it to immutable and store it back in the dictionary.
NSMutableArray *tmpMutableArray = [NSMutableArray arrayWithArray:[tmpMutableDic objectForKey:obj.key]];
[tmpMutableArray addObject:obj];
[tmpMutableDic setObject:[tmpMutableArray copy] forKey:obj.key];
}
}
// Return an immutable version of the dictionary.
return [tmpMutableDic copy];
}