Add values in NSMutableDictionary in iOS with Objective-C

Miguel E picture Miguel E · Jun 29, 2011 · Viewed 87.7k times · Source

I'm starting objective-c development and I would like to ask the best way to implement a list of keys and values.

In Delphi there is the class TDictionary and I use it like this:

myDictionary : TDictionary<string, Integer>;

bool found = myDictionary.TryGetValue(myWord, currentValue);
if (found)
{
    myDictionary.AddOrSetValue(myWord, currentValue+1);
} 
else
{
    myDictionary.Add(myWord,1);
}

How can I do it in objective-c? Is there equivalent functions to the above mentioned AddOrSetValue() or TryGetValue()?

Thank you.

Answer

Tom Jefferys picture Tom Jefferys · Jun 29, 2011

You'd want to implement your example along these lines:

EDIT:

//NSMutableDictionary myDictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];

NSNumber *value = [myDictionary objectForKey:myWord];

if (value)
{
    NSNumber *nextValue = [NSNumber numberWithInt:[value intValue] + 1];
    [myDictionary setObject:nextValue  forKey:myWord];
} 
else
{
    [myDictionary setObject:[NSNumber numberWithInt:1] forKey:myWord]
}

(Note: you can't store ints or other primitives directly in a NSMutableDictionary, hence the need to wrap them in an NSNumber object, and make sure you call [myDictionary release] when you've finished with the dictionary).