NSDictionary初始化
//1.創(chuàng)建空的字典
NSDictionary *dict=[[NSDictionary alloc]init];
//或者 NSDictionary *dict=[NSDictionary dictionary];
//2.
NSDictionary *dict1=[[NSDictionary alloc]initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];
//或者 NSDictionary *dict1=[NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];
//3.讀取文件數(shù)據(jù)
// 獲取Documents目錄路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSDictionary *dict2=[[NSDictionary alloc]initWithContentsOfFile:docDir];
//或者 NSDictionary *dict1=[NSDictionary dictionaryWithContentsOfFile:docDir];
常用方法
//獲取字典數(shù)量
NSInteger count=[dict1 count];
//通過(guò)key獲取對(duì)應(yīng)的value對(duì)象
NSObject *valueObj=[dict1 objectForKey:@"key"];
//將字典的key轉(zhuǎn)換成枚舉對(duì)象,用于遍歷
NSEnumerator *enumerator=[dict1 keyEnumerator];
//獲取所有值的集合
NSArray *keys=[dict1 allKeys];
//獲取所有值的集合
NSArray *values=[dict1 allValues];
可變數(shù)組NSMutableDictionary
//初始化一個(gè)空的可變字典
NSMutableDictionary *mutableDic1 = [NSMutableDictionary dictionary];
//或者 NSMutableDictionary *mutableDic1=[[NSMutableDictionary alloc]init];
NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];
NSDictionary *mutableDic3 = [NSDictionary dictionaryWithObject:@"v3" forKey:@"key3"];
//向字典2對(duì)象中添加整個(gè)字典對(duì)象3
[mutableDic2 addEntriesFromDictionary:mutableDic3];
//向字典2對(duì)象中最佳一個(gè)新的key3和value3
[mutableDic2 setValue:@"value3" forKey:@"key3"];
//將空字典1對(duì)象內(nèi)容設(shè)置與字典2對(duì)象相同
[mutableDic1 setDictionary:mutableDic2];
//將字典中key1對(duì)應(yīng)的值刪除
[mutableDic1 removeObjectForKey@"key1"];
//根據(jù)指定的數(shù)組(key)移除字典1的內(nèi)容
NSArray *array = [NSArray arrayWithObjects:@"key1", nil];
[mutableDic2 removeObjectsForKeys:array];
//移除字典所有對(duì)象
[mutableDic1 removeAllObjects];
遍歷字典
//快速枚舉
for (id key in dic){
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
//一般枚舉
NSArray *keys = [dic allKeys];
int length = [keys count];
for (int i = 0; i < length;i++){
id key = [keys objectAtIndex:i];
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
}
//通過(guò)枚舉類型枚舉
NSEnumerator *enumerator = [dic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
key = [enumerator nextObject];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。