2010-08-09 57 views
8

请告诉我如何让NSMutableDictionary中的同一个键具有多个值? 因为当我使用下面的方法,这些值是替换最近一个在Objective-C编程中单键保存多个值的NSMutableDictionary

在我的情况:

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

时,我认为词典的内容,我只得到了关键代码reminderDate。这里的代码对于所有值都是相同的。帮助我如何避免名称和姓氏被计划提醒取代。

谢谢

回答

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. 
    
+9

不要只是downvote,让我知道什么是错的,以便我可以修复它! – dreamlax 2014-06-20 09:29:10

1

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

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

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

[dictionary setObject:d forKey:[NSNumber numberWithint:code]]; 
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建议的那样,但是如果你正在处理一个字典,你想为一个键存储一个数组,而且该数组中的对象本身没有特定的键,这是一个解决方案!

+0

为什么不简单地使用'NSString * dummy = stringWithFormat:@“%@,%@,%@”,forename,surname,reminderDate];'。至少,你应该使用'NSMutableString',如果你是以这种方式连接的话。 – dreamlax 2013-10-04 16:20:06

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"]; 
相关问题