標籤:eve nil sar 包含 table 刪除 str san log
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];
以檔案內容初始化字典
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 [email protected]"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];
}
IOS Intro - NSDictionary and NSMutableDictionary