Add values in NSMutableDictionary in iOS with Objective-C

自古美人都是妖i 提交于 2019-12-03 05:10:19
Tom Jefferys

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).

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

[myDictionary setObject:nextValue  forKey:myWord];

You can simply say:

myDictionary[myWord] = nextValue;

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

Yep:

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

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

Edit:

Example:

- (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 there exists a more compact approach:

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

Crazy indentation for readability.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!