一、NSDictionary (不可變字典) 數組
字典的初始化 spa
//一個key - value 對象
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"@123" forKey:@"key1"]; 繼承
//兩個以上 key - value rem
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2" ,nil]; it
//用字典爲另外一個子字典初始化 io
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic1] table
//新方法賦值 object
NSDictionary *dic4 = @{@"key1": @"value1",@"key2": @"value2"}; 遍歷
//覺得件內容初始化一個字典
NSDictionary *dic5 = [NSDictionary dictionaryWithContentsOfFile:path];
//將字典的key轉成一個枚舉對象,用於遍歷
NSEnumerator *enumerator = [dic4 keyEnumerator];
字典的經常使用方法
//返回字典鍵值對的個數
NSInteger count = [dic4 count];
//經過key獲取對應的value對象
NSObject *object = [dic2 objectForKey:@"key1"];
//獲取全部鍵的集合
NSArray *keys = [dic3 allKeys];
//獲取全部值的集合
NSArray *values = [dic3 allValues];
一、NSMutableDictionary (可變字典,繼承自NSDictionary)
可變字典與不可變字典的初始化方法相同,但不能用新方法。下面只介紹經常使用方法
經常使用方法
NSMutableDictionary *dic6 = [NSMutableDictionary dictionary];
//像字典中追加一個新的 key5 和 value5
[dic6 setObject:@"value5" forKey:@"key5"];
//像字典中添加整個字典對象
[dic6 addEntriesFromDictionary:dic1];
//將字典6的對象內容設置與字典1的對象內容相同
[dic6 setDictionary:dic1];
//刪除鍵所對應的鍵值對
[dic6 removeObjectForKey:@"key1"];
//刪除數組中的全部key 對應的鍵值對
NSArray *array = @[@"key1",@"key2",@"key3"];
[dic6 removeObjectsForKeys:array];
//移除字典中的全部對象
[dic6 removeAllObjects];
遍歷字典
通常遍歷
for (int i = 0; i < [dic3 count]; i++) {
id key = [keys objectAtIndex:i];
id obj = [dic3 objectForKey:key];
NSLog(@"%@",obj);
}
快速遍歷
for (id key in dic3) {
id obj = [dic3 objectForKey:key];
NSLog(@"%@",obj);
}
枚舉的辦法遍歷
NSEnumerator *enumerator = [dic4 keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic4 objectForKey:key];
NSLog(@"%@",obj);
key = [enumerator nextObject];
}