1.不可變詞典NSDictionary
代碼如下 復制代碼字典初始化
NSNumber *numObj = [NSNumber numberWithInt:100];
以一個元素初始化
NSDictionary *dic = [NSDictionary dictionaryWithObject:numObj forKey:@"key"];
初始化兩個元素
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:numObj, @"valueKey", numObj2, @"value2",nil];
初始化新字典,新字典包含otherDic
NSDictionary *dic = [NSDictionary dictionaryWithDictionary:otherDic];
以文件內容初始化字典
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
常用方法
獲取字典數量
NSInteger count = [dic count];
通過key獲取對應的value對象
NSObject *valueObj = [dic objectForKey:@"key"];
將字典的key轉成枚舉對象,用於遍歷
NSEnumerator *enumerator = [dic keyEnumerator];
獲取所有鍵的集合
NSArray *keys = [dic allKeys];
獲取所有值的集合
NSArray *values = [dic allValues];
2.可變數組NSMutableDictionary
初始化一個空的可變字典
NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];
代碼如下 復制代碼NSDictionary *dic3 = [NSDictionary dictionaryWithObject:@"v3" forKey:@"key3"];
向字典2對象中添加整個字典對象3
代碼如下 復制代碼[dic2 addEntriesFromDictionary:dic3];
向字典2對象中最佳一個新的key3和value3
代碼如下 復制代碼[dic2 setValue:@"value3" forKey:@"key3"];
初始化一個空的可變字典
代碼如下 復制代碼NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
將空字典1對象內容設置與字典2對象相同
代碼如下 復制代碼[dic1 setDictionary:dic2];
將字典中key1對應的值刪除
代碼如下 復制代碼[dic1 removeObjectForKey@"key1"];
NSArray *array = [NSArray arrayWithObjects:@"key1", nil];
根據指定的數組(key)移除字典1的內容
代碼如下 復制代碼[dic2 removeObjectsForKeys:array];
移除字典所有對象
代碼如下 復制代碼[dic1 removeAllObjects];
遍歷字典
快速枚舉
代碼如下 復制代碼for (id key in dic){
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
一般枚舉
代碼如下 復制代碼NSArray *keys = [dic allKeys];
inr length = [keys count];
for (int i = 0; i < length;i++){
id key = [keys objectAtIndex:i];
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
通過枚舉類型枚舉
代碼如下 復制代碼NSEnumerator *enumerator = [dic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
key = [enumerator nextObject];
}