標籤:
字典是用於儲存具有映射關係(key-value對)的資料集合.一個key-value對認為是一個條目(Entry),字典是儲存key-value對的容器.
字典類的特點
與數組不同,字典靠key存取元素;
key值不能重複,value必須是對象;
索引值對在字典中是無序儲存的.
字典分為不可變字典(NSDictionary)和可變字典(NSMutableDictionary).
不可變字典(NSDictionary)
字典一旦建立,索引值對不可更改,不可添加, 不可刪除.
僅能讀取key或value.
建立字典對象
1 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"張三" forKey:@"name"];2 NSLog(@"dic1 %@", dic1);
建立有多個key-value對的字典
1 NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"a", @"1", @"b", @"2", @"c", @"3", nil];2 NSLog(@"dic2 %@", dic2);3 //擷取所有的key4 NSLog(@"key %@", dic2.allKeys);5 // 擷取所有的value6 NSLog(@"value %@", dic2.allValues);7 // 通過key 找 value8 // 根據key擷取對應value9 NSLog(@"object %@", [dic2 objectForKey:@"2"]);
可變字典(NSMutableDictionary)
建立可變字典
1 NSMutableDictionary *mDic = [NSMutableDictionary dictionary];2 [mDic setObject:@"lilei" forKey:@"name"];3 [mDic setObject:@"m" forKey:@"sex"];4 NSLog(@"mDic %@", mDic);
添加/修改key-value對
1 // 當key不存在的時候 添加key-value對2 // 當key存在的時候 找到對應的key 替換對應value內容3 [mDic setObject:@"lilei" forKey:@"name"];4 [mDic setObject:@"male" forKey:@"sex"];5 NSLog(@"mDic %@", mDic);6 // 修改7 [mDic setObject:@"hanmeimei" forKey:@"name"];8 NSLog(@"mDic %@", mDic);
刪除字典
1 // 刪除2 [mDic removeObjectForKey:@"name"];3 NSLog(@"mDic %@", mDic);
遍曆字典
1 // 遍曆字典 2 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"lilei", @"name", @"male", @"sex", @"18", @"age", nil]; 3 NSLog(@"dic %@", dic); 4 NSArray *arr1 = dic.allKeys; 5 for (NSInteger i = 0; i < arr1.count; i++) { 6 // 擷取每一個key值 7 NSString *key = [arr1 objectAtIndex:i]; 8 // 根據key擷取對應value 9 NSLog(@"key: %@, value: %@", key, [dic objectForKey:key]);10 }
Objective-C中字典類