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

我正在开始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); } 

我怎么能在objective-c做到这一点? 是否有与上面提到的AddOrSetValue() or TryGetValue()等价的函数?

谢谢。

你可能想要按照以下的方式来实现你的例子:

编辑:

 //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] } 

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

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

 [myDictionary setObject:nextValue forKey:myWord]; 

你可以简单地说:

 myDictionary[myWord] = nextValue; 

同样,要获得一个值,可以使用myDictionary[key]来获取值(或零)。

是的:

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

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 } 

Reedit:对于具体的例子,有一个更紧凑的方法:

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

疯狂的缩进可读性。