NSMutableDictionary添加对象

时间:2009-07-12 22:45:31

标签: objective-c nsmutabledictionary

是否有更有效的方法将对象添加到NSMutableDictionary而不是简单的迭代?示例:

// Create the dictionary

NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];    

// Add the entries

[myMutableDictionary setObject:@"Stack Overflow" forKey:@"http://stackoverflow.com"];
[myMutableDictionary setObject:@"SlashDotOrg" forKey:@"http://www.slashdot.org"];
[myMutableDictionary setObject:@"Oracle" forKey:@"http://www.oracle.com"];

好奇,我确信这就是它必须要做的事。

4 个答案:

答案 0 :(得分:20)

NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSNumber numberWithDouble:acceleration.x], @"x",
  [NSNumber numberWithDouble:acceleration.y], @"y",
  [NSNumber numberWithDouble:acceleration.z], @"z",
  [NSDate date], @"date", 
  nil];

答案 1 :(得分:15)

如果您事先拥有所有对象和键,则可以使用NSDictionary:

对其进行初始化
dictionaryWithObjects:forKeys:

当然这会给你不可变的字典不可变。这取决于你使用哪一个你需要的,你可以从NSDictionary获得一个可变副本,但在这种情况下使用原始代码似乎更容易:

NSDictionary * dic = [NSDictionary dictionaryWith....];
NSMutableDictionary * md = [dic mutableCopy];
... use md ...
[md release];

答案 2 :(得分:8)

请允许我向正在开始的人添加一些信息。

可以使用objective-c literals创建一个语句更友好的NSDictionary

NSDictionary *dict = @{ 
    key1 : object1, 
    key2 : object2, 
    key3 : object3 };

答案 3 :(得分:0)

NSMutableDictionary *example = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@5,@"burgers",@3, @"milkShakes",nil];

对象在键之前。