Java有Map,可以把資料以索引值對的形式儲存起來,取值的時候通過key就可以直接拿到對應的值,方便快捷。在Objective-C語言中,詞典就是做這樣的事情的,和NSArray一樣,一個詞典對象也能儲存不同類型的值,詞典也分別有不可變詞典和可變的詞典(NSDictionary與NSMutableDictionary),前者是安全執行緒的,後者不是 。
1、不可變詞典NSDictionary的主要用法:
[NSDictionary dictionaryWithObjectsAndKeys:..] : 使用索引值對直接建立詞典對象,結尾必需使用nil標誌結束。
[dictionary count]: 得到詞典的索引值對數量。
[dictionary keyEnumerator]: 將詞典的所有key儲存在NSEnumerator中,類似於Java語言中的迭代器
[dictionary objectEnumerator]: 將詞典的所有value儲存在NSEnumerator中
[dictionary objectForKey:key]: 通過傳入key對象可以拿到當前key對應儲存的值。
程式碼範例:
int main(int argc, const char * argv[]){ @autoreleasepool { NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"25",@"age",@"張三",@"name",@"男",@"性別",nil]; NSLog(@"%lu", [dictionary count]); NSEnumerator *enumeratorKey = [dictionary keyEnumerator]; for (NSObject *object in enumeratorKey) { NSLog(@"key:%@", object); } NSEnumerator *enumeratorObject = [dictionary objectEnumerator]; for (NSObject *object in enumeratorObject) { NSLog(@"value:%@", object); } NSLog(@"key name的值是:%@", [dictionary objectForKey:@"name"]); } return 0;}
列印結果;
2012-07-09 16:31:18.276 objectiveC[2965:403] 32012-07-09 16:31:18.282 objectiveC[2965:403] key:age2012-07-09 16:31:18.282 objectiveC[2965:403] key:name2012-07-09 16:31:18.283 objectiveC[2965:403] key:性別2012-07-09 16:31:18.283 objectiveC[2965:403] value:252012-07-09 16:31:18.284 objectiveC[2965:403] value:張三2012-07-09 16:31:18.284 objectiveC[2965:403] value:男2012-07-09 16:31:18.285 objectiveC[2965:403] key name的值是:張三
2、可變的詞典NSMutableDictionary。
NSMutableDictionary是NSDictionary的子類,所以繼承了NSDictionary的方法, 以上的代碼對NSMutableDictionary來說完全可用。我們試試不一樣的地方
增刪索引值資料。
[dictionary setObject: forKey:] :向可變的詞典動態添加資料
[dictionary removeAllObjects..] : 刪除掉詞典中的所有資料。
[dictionary removeObjectForKey..] :刪除掉詞典中指定key的資料
程式碼範例:
int main(int argc, const char * argv[]){ @autoreleasepool { NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"25",@"age",@"張三",@"name",@"男",@"性別",nil]; [dictionary setObject:@"30名" forKey:@"名次"]; NSLog(@"%lu", [dictionary count]); NSEnumerator *enumeratorKey = [dictionary keyEnumerator]; for (NSObject *object in enumeratorKey) { NSLog(@"key:%@", object); } NSEnumerator *enumeratorObject = [dictionary objectEnumerator]; for (NSObject *object in enumeratorObject) { NSLog(@"value:%@", object); } NSLog(@"key 名次的值是:%@", [dictionary objectForKey:@"名次"]); [dictionary removeObjectForKey:@"名詞"]; NSLog(@"%lu", [dictionary count]); } return 0;}
列印結果:
2012-07-09 16:37:07.037 objectiveC[3053:403] 42012-07-09 16:37:07.042 objectiveC[3053:403] key:age2012-07-09 16:37:07.043 objectiveC[3053:403] key:性別2012-07-09 16:37:07.043 objectiveC[3053:403] key:name2012-07-09 16:37:07.044 objectiveC[3053:403] key:名次2012-07-09 16:37:07.044 objectiveC[3053:403] value:252012-07-09 16:37:07.045 objectiveC[3053:403] value:男2012-07-09 16:37:07.045 objectiveC[3053:403] value:張三2012-07-09 16:37:07.046 objectiveC[3053:403] value:30名2012-07-09 16:37:07.046 objectiveC[3053:403] key 名次的值是:30名