2016-01-11 88 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:我更新了,我相信你很清楚編輯部分。 –