使用Objective-C在iOS中的NSMutableDictionary中添加值

Mig*_*l E 16 objective-c nsmutabledictionary ios

我正在开始objective-c开发,我想问一下实现键和值列表的最佳方法.

在Delphi中有类TDictionary,我使用它是这样的:

myDictionary : TDictionary<string, Integer>;

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

我怎么能这样做objective-c?是否有与上述相同的功能AddOrSetValue() or TryGetValue()

谢谢.

Tom*_*rys 51

您想要沿着以下几行实现您的示例:

编辑:

//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]
}
Run Code Online (Sandbox Code Playgroud)

(注意:您不能直接在其中存储整数或其他基元NSMutableDictionary,因此需要将它们包装在一个NSNumber对象中,并确保[myDictionary release]在完成字典时调用).


Jes*_*sak 9

其他答案是正确的,但现在有更多的现代语法.而不是:

[myDictionary setObject:nextValue  forKey:myWord];
Run Code Online (Sandbox Code Playgroud)

你可以简单地说:

myDictionary[myWord] = nextValue;
Run Code Online (Sandbox Code Playgroud)

同样,要获取值,您可以使用myDictionary[key]获取值(或nil).


Wil*_*and 5

是的:

- (id)objectForKey:(id)key;
- (void)setObject:(id)object forKey:(id)key;
Run Code Online (Sandbox Code Playgroud)

setObject:forKey:用相同的键覆盖任何现有对象;如果对象不存在,则objectForKey:返回nil

编辑:

例:

- (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
}
Run Code Online (Sandbox Code Playgroud)

重新编辑:对于特定示例,存在一种更紧凑的方法:

[dict
  setObject:
    [NSNumber numberWithInteger:([[dict objectForKey:@"key"] integerValue] + 1)]
  forKey:
    @"key"
 ];
Run Code Online (Sandbox Code Playgroud)

疯狂缩进以提高可读性。