一:字典的基本概念
創(chuàng)新互聯(lián)主要從事成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)內(nèi)江,10多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專(zhuān)業(yè),歡迎來(lái)電咨詢(xún)建站服務(wù):18982081108
Foundation中的字典(NSDictionary,NSMutableDictionary)是由鍵-值對(duì)組成的數(shù)據(jù)集合.正如,我們?cè)谧值淅锊檎覇卧~的定義一樣.
通過(guò)key(鍵),查找的對(duì)應(yīng)的value(值),key通常是字符串對(duì)象,也可以是其他任意類(lèi)型對(duì)象.在一個(gè)字典對(duì)象中,key的值必須是唯一的.
此外,字典對(duì)象的鍵和值不可以為空(nil),如果需要在字典中加入一個(gè)空值,可以加入NSNull對(duì)象
二:不可變字典-NSDictionary
1:初始化(以一個(gè)元素和多個(gè)元素進(jìn)行初始化):
//以一個(gè)鍵值對(duì)象 進(jìn)行初始化
NSDictionary*dict1=[NSDictionary dictionaryWithObject:numObj1 forKey:@"key1"];NSLog(@"%@",dict1);//以多個(gè)元素進(jìn)行初始化NSDictionary*dict2=[NSDictionary dictionaryWithObjectsAndKeys:numObj1,@"key1",numObj2,@"key2", nil];NSLog(@"%@",dict2);
2:獲取字典的數(shù)量
//獲取字典的數(shù)量
NSInteger count=[dict2count];
NSLog(@"%ld",count);
3:根據(jù)key獲取相應(yīng)的value對(duì)象
//根據(jù)key獲取相應(yīng)的value對(duì)象
NSString*value=[dict2 objectForKey:@"key1"];NSLog(@"%@",value);4:把字典的key轉(zhuǎn)換成枚舉對(duì)象用于遍歷NSEnumerator*enumerator=[dict2 keyEnumerator];
5:獲取所有的key集合//獲取所有的key集合
NSArray*keys=[dict2 allKeys];NSLog(@"%@",keys);6:獲取所有的value集合//獲取所有的value集合
NSArray*values=[dict2 allValues];NSLog(@"%@",values);三:可變字典N(xiāo)SMutableDictionary繼承自NSDictionary1:初始化字典
//初始化字典N(xiāo)SMutableDictionary*mutableDic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5", nil];2:向字典中添加指定的字典//向一個(gè)字典中添加一個(gè)字典
NSDictionary*dict4=[NSDictionary dictionaryWithObject:@"v6" forKey:@"k6"];[mutableDic addEntriesFromDictionary:dict4];NSLog(@"%@",mutableDic);3:向字典中添加value和key
//向字典中添加value和key[mutableDicsetValue:@"object" forKey:@"key"];4:創(chuàng)建空的字典,然后設(shè)置新的一個(gè)字典//創(chuàng)建空的字典,然后設(shè)置新的一個(gè)字典,把會(huì)之前的字典全部覆蓋掉NSMutableDictionary*mutableDict2=[NSMutableDictionary dictionary];[mutableDict2setDictionary:mutableDic];NSLog(@"%@",mutableDict2);5:刪除指定key的value值//移除指定key的value值[mutableDict2 removeObjectForKey:@"k4"];NSLog(@"%@",mutableDict2);6:刪除移除key集合的value值//刪除一組key的value值NSArray*arrayKeys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil];[mutableDict2 removeObjectsForKeys:arrayKeys];NSLog(@"%@",mutableDict2);7:刪除字典中所有的value//刪除字典中所有的數(shù)據(jù)
[mutableDict2 removeAllObjects];NSLog(@"%@",mutableDict2);四:枚舉遍歷1:一般遍歷
//一般遍歷
NSArray*allKeys=[mutableDic allKeys];for(NSInteger i=0; i<[allKeys count]; i++){ NSString*obj=[mutableDic objectForKey:[allKeys objectAtIndex:i]]; NSLog(@"%@",obj);}2:快速枚舉
//快速遍歷
for(id key in mutableDic){NSString*object=[mutableDic objectForKey:key];NSLog(@"%@",object);}3:迭代器枚舉//枚舉器NSEnumerator*enumerator1=[mutableDic keyEnumerator]; id key=[enumerator1 nextObject];while(key){ id object=[mutableDic objectForKey:key]; NSLog(@"%@",object); key=[enumerator1 nextObject];}