[ACCEPTED]-Add values in NSMutableDictionary in iOS with Objective-C-nsmutabledictionary

Accepted answer
Score: 53

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


//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];
    [myDictionary setObject:[NSNumber numberWithInt:1] forKey:myWord]

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

Score: 11

The other answers are correct, but there 4 is more modern syntax for this now. Rather 3 than:

[myDictionary setObject:nextValue  forKey:myWord];

You can simply say:

myDictionary[myWord] = nextValue;

Similarly, to get 2 a value, you can use myDictionary[key] to get the value (or 1 nil).

Score: 6


- (id)objectForKey:(id)key;
- (void)setObject:(id)object forKey:(id)key;

setObject:forKey: overwrites any existing object with 4 the same key; objectForKey: returns nil if the object doesn't 3 exist.



- (void)doStuff {
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];

  [dict setObject:@"Foo" forKey:@"Key_1"]; // adds @"Foo"
  [dict setObject:@"Bar" forKey:@"Key_2"]; // adds @"Bar"

  [dict setObject:@"Qux" forKey:@"Key_2"]; // overwrites @"Bar"!

  NSString *aString = [dict objectForKey:@"Key_1"]; // @"Foo"
  NSString *anotherString = [dict objectForKey:@"Key_2"]; // @"Qux"
  NSString *yas = [dict objectForKey:@"Key_3"]; // nil

Reedit: For the specific example 2 there exists a more compact approach:

    [NSNumber numberWithInteger:([[dict objectForKey:@"key"] integerValue] + 1)]

Crazy 1 indentation for readability.

More Related questions