NSDictionary松申、NSMutableDictionary的基本用法
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];
以文件內(nèi)容初始化字典
NSDictionary *dic?=?[NSDictionary dictionaryWithContentsOfFile:path];
常用方法
獲取字典數(shù)量
NSInteger count =?[dic count];
通過key獲取對應(yīng)的value對象
NSObject *valueObj?=?[dic objectForKey:@"key"];
將字典的key轉(zhuǎn)成枚舉對象凿叠,用于遍歷
NSEnumerator *enumerator?=?[dic keyEnumerator];
獲取所有鍵的集合
NSArray *keys?=?[dic allKeys];
獲取所有值的集合
NSArray *values?=?[dic allValues];
2.可變數(shù)組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對象內(nèi)容設(shè)置與字典2對象相同
[dic1 setDictionary:dic2];
將字典中key1對應(yīng)的值刪除
[dic1 removeObjectForKey@"key1"];
NSArray *array?=?[NSArray arrayWithObjects:@"key1", nil];
根據(jù)指定的數(shù)組(key)移除字典1的內(nèi)容
[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];
}