NSDictionary/NSMutableDictionary特色:android
(1)裏存儲的東西都是鍵值對編程
(2)能夠像數組同樣快速建立(適用NSDictionary):@{key1 : value1, key2 : value2}數組
(3)快速訪問元素:字典名 [key]spa
好比能夠這樣爲指定key賦值:對象
dic [@」key1」] = @」value1」;rem
快速獲取key所對應的value:it
NSString *name = dic[@」name」];//存儲的是Stringio
或者:table
NSDictionary *userdic = dic[@」user」];//存儲的是NSDictionaryobject
NSString *name = userdic [@」name」];
(4)字典不容許有相同的key,但容許有相同的value(Object)
(5)字典是無序的
1、不可變詞典NSDictionary
字典初始化:
(1)以一個元素初始化
NSDictionary *dic = [NSDictionary dictionaryWithObject:numObj forKey:@"key"];
(2)初始化兩個元素
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
numObj, @"valueKey", numObj2, @"value2",nil];
(3)初始化新字典,新字典包含otherDic
NSDictionary *dic = [NSDictionary dictionaryWithDictionary:otherDic];
(4)以文件內容初始化字典
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
(1)也可建立多維字典
使用快速建立的方式:
NSArray *persons = @[
@{@"name" : @"jack", @"qq" : @"432423423", @"books": @[@"5分鐘突破iOS編程", @"5分鐘突破android編程"]},
@{@"name" : @"rose", @"qq" : @"767567"},
@{@"name" : @"jim", @"qq" : @"423423"},
@{@"name" : @"jake", @"qq" : @"123123213"}
];
訪問:
NSLog(@"%@", persons[1][@"qq"]);
上述代碼含義:
先取出1位置對應的字典
再取出字典中qq這個key對應的數據
經常使用方法:
(1)獲取字典數量
NSInteger count = [dic count];
(2)經過key獲取對應的value對象
NSObject *valueObj = [dic objectForKey:@"key"];
(3)將字典的key轉成枚舉對象,用於遍歷
NSEnumerator *enumerator = [dic keyEnumerator];
(4)獲取全部鍵的集合
NSArray *keys = [dic allKeys];
(5)獲取全部值的集合
NSArray *values = [dic allValues];
2、可變數組NSMutableDictionary
(1)初始化一個空的可變字典
NSMutableDictionary *dic2 = [NSMutableDictionary
dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObject:
@"v3" forKey:@"key3"];
(2)向字典2對象中添加整個字典對象3
[dic2 addEntriesFromDictionary:dic3];
(3)向字典2對象中最佳一個新的key3和value3
[dic2 setValue:@"value3" forKey:@"key3"];
(4)初始化一個空的可變字典
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
(5)將空字典1對象內容設置與字典2對象相同
[dic1 setDictionary:dic2];
(6)將字典中key1對應的值刪除
[dic1 removeObjectForKey@"key1"];
NSArray *array = [NSArray arrayWithObjects:@"key1", nil];
(7)根據指定的數組(key)移除字典1的內容
[dic2 removeObjectsForKeys:array];
(8)移除字典全部對象
[dic1 removeAllObjects];
3、遍歷字典
(1)快速枚舉
for (id key in dic){
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
(2)通常枚舉
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);
}
(3)經過枚舉類型枚舉
NSEnumerator *enumerator = [dic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
key = [enumerator nextObject];
}