2016-01-11 89 views
-2

如何在Objective-C的字典中存储数组。我该如何修改我的代码?如何在字典中存储数组

studentDict=[[NSMutableDictionary alloc]init]; 
studentArray=[[NSMutableArray alloc]init]; 

[studentArray addObject:name.text]; 
[studentArray addObject:regno.text]; 
[studentArray addObject:marks.text]; 
[studentArray addObject:rank.text]; 
studentDict=[NSMutableDictionary dictionaryWithObjects:[NSMutableArray arrayWithObjects:studentArray, nil] forKeys:[NSMutableArray arrayWithObjects:studentArray, nil]]; 
NSLog(@"%@",studentArray); 
+0

'NSDictionary * studentsDictionary = @ {@“students”:studentArray};' – Zhang

回答

1

坚持变量名称,它使您的代码可读性和不易出错。 如果你有一个名为“studentArray”的数组,那么它应该只存储Student类的对象。

Student *firstStudent = ....; 
    Student *secondStudent = .... ; 
    NSArray *studentArray = @[firstStudent, secondStudent]; 

现在,你想这个数组存储在词典:

NSDictioanary *someDictionary = @{@"studentArrayKey" : studentArray 
             @"otherKey" : @"otherObject", 
           }; 

编辑:

如果你的名字studentArraystudents按对象 - 命名约定这将是很好。名称复数时,所有收集听起来都很好

+0

好的回答....对我很有帮助。 –

+0

@JAGAT:我更新了,我相信你很清楚编辑部分。 –