NSMutableDictionary使用单个键在Objective-C编程中保存许多值

时间:2010-08-09 06:53:31

标签: objective-c nsmutabledictionary

请告诉我如何在NSMutableDictionary中为同一个键设置多个值?

当我使用以下方法时,值将被最近的值替换。

就我而言:

[dictionary setObject:forename forKey:[NSNumber numberWithint:code]];
[dictionary setObject:surname forKey:[NSNumber numberWithint:code]];
[dictionary setObject:reminderDate forKey:[NSNumber numberWithint:code]];

当我查看字典的内容时,我只获得了reminderDate的密钥代码。这里,所有值的代码都相同。如何避免将姓氏和姓氏替换为plannedReminder

谢谢!

4 个答案:

答案 0 :(得分:15)

您似乎使用code作为密钥,并且希望根据code表示多个值。在这种情况下,您应该:

  1. 将与code相关联的所有数据抽象到一个单独的类(可能称为Person)中,并将此类的实例用作字典中的值。

  2. 使用多个词典层:

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    
    NSMutableDictionary *firstOne = [NSMutableDictionary dictionary];
    [firstOne setObject:forename forKey:@"forename"];
    [firstOne setObject:surname forKey:@"surname"];
    [firstOne setObject:reminderDate forKey:@"reminderDate"];
    
    [dictionary setObject:firstOne forKey:[NSNumber numberWithInt:code]];
    
    // repeat for each entry.
    

答案 1 :(得分:5)

如果你真的坚持在字典中存储对象,并且如果你正在处理字符串,你总是可以用逗号分隔所有字符串,然后当你从密钥中检索对象时,你将会将所有对象都放在准csv格式中!然后,您可以轻松地将该字符串解析为对象数组。

以下是您可以运行的示例代码:

NSString *forename = @"forename";
NSString *surname = @"surname";
NSString *reminderDate = @"10/11/2012";
NSString *code = @"code";

NSString *dummy = [[NSString alloc] init];
dummy = [dummy stringByAppendingString:forename];
dummy = [dummy stringByAppendingString:@","];
dummy = [dummy stringByAppendingString:surname];
dummy = [dummy stringByAppendingString:@","];
dummy = [dummy stringByAppendingString:reminderDate];
dummy = [dummy stringByAppendingString:@","];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:dummy forKey:code];

然后检索并解析字典中的对象:

NSString *fromDictionary = [dictionary objectForKey:code];
NSArray *objectArray = [fromDictionary componentsSeparatedByString:@","];
NSLog(@"object array: %@",objectArray);

它可能不像像dreamlax建议的字典层一样干净,但如果你正在处理一个字典,你想要为一个键存储一个数组,而该数组中的对象本身没有特定的键,这是一个解决方案!

答案 2 :(得分:2)

我认为您不了解字典是如何工作的。每个键只能有一个值。你想要一本字典词典或数组字典。

在这里,您可以为每个人创建一个字典,然后将其存储在主字典中。

NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
forename, @"forename", surname, @"surname", @reminderDate, "@reminderDate", nil];

[dictionary setObject:d forKey:[NSNumber numberWithint:code]];

答案 3 :(得分:1)

现代语法更清晰。

一个。如果您在加载时构建静态结构:

NSDictionary* dic = @{code : @{@"forename" : forename, @"surname" : surnamem, @"reminderDate" : reminderDate}/*, ..more items..*/};

B中。如果您实时添加项目(可能):

NSMutableDictionary* mDic = [[NSMutableDictionary alloc] init];
[mDic setObject:@{@"forename" : forename, @"surname" : surnamem, @"reminderDate" : reminderDate} forKey:code];
//..repeat

然后您作为2D词典进行访问......

mDic[code][@"forename"];