字典:
1、字典是一個(gè)對(duì)象;(NSDictionary類(lèi)創(chuàng)建)
2、字典以鍵值對(duì)形式存儲(chǔ)信息;
3、 字典鍵值對(duì): key(鍵) :一般是字符串對(duì)象, value(值):可以是任意對(duì)象;
4、key必須是唯一;
5、value可以不唯一;
特征:
1.字典一定是成對(duì)存在的 鍵值對(duì)
2.字典是無(wú)序集合 (不能通過(guò)下標(biāo)來(lái)獲取值)
3.通過(guò)key來(lái)獲取value (key一般都是字符串對(duì)象,value可以是任意對(duì)象)
NSDictionary的創(chuàng)建(不可變,一旦創(chuàng)建,內(nèi)容就不能添加/刪除改動(dòng)):
1 實(shí)例化方法:
a)NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"one",@"2",@"two", nil];
b)NSDictionary *dict2=[[NSDictionary alloc]initWithObjects:@[@"4",@"5",@"6"]forKeys:@[@"four",@"five",@"six”]]
c) NSDictionary *dict3 = [[NSDictionary alloc] initWithDictionary:dict]
d) 通過(guò)鍵值對(duì)創(chuàng)建:
NSDictionary *dict4 = @{@"紅臉":@"關(guān)羽",@"黑臉":@"張飛"};
NSDictionary常用方法:
1 獲取鍵值對(duì)個(gè)數(shù):
NSInteger count = [dict count] / dict.count
2 通過(guò)key獲取value值 :
a)NSString *str = [dict valueForKey:@"德瑪西亞"]
b)NSString *str2 = dict[@"不祥之刃"]
3 快速枚舉遍歷數(shù)組得到所有的key:
for(NSString *s in dict)
{
NSLog(@"%@",s);
}
4 獲取字典中所有的key:
NSArray *arr = [dict allKeys];
for(NSString *s in arr)
{
NSLog(@"%@",s);
}
5 獲取字典中所有的value值:
NSArray *valueArr = [dict allValues];
for(NSString *s in valueArr)
{
NSLog(@"%@",s);
}
6 使用block方法遍歷:
[dict enumerateKeysAndObjectsUsingBlock:^(id key , id obj ,BOOL *stop){
NSLog(@“%@=%@”,key,obj);
}];
7 把字典保存到文件中:
[dict writeToFile:@"/Users/qianfeng/desktop/dict.plist" atomically:YES]
返回值為BOOL類(lèi)型
8 從文件中讀取字典:
NSDictionary *readDict=[NSDictionary dictionaryWithContentsOfFile:@"/Users/qianfeng/desktop/dict.plist"]
NSMutableDictionary常用方法:
1 增加:
a)增加一組鍵值對(duì):[dictM setObject:@"1" forKey:@"one"]
注:setObject: forKey 字典中存在key 修改當(dāng)前key的value值 字符中不存在key 增加一對(duì)鍵值對(duì)
b) 增加整個(gè)字典:[dictM addEntriesFromDictionary:@{@"two":@"2",@"three":@"3"}]
2 刪除:
a)刪除一組鍵值對(duì)(通過(guò)key值刪除):[dictM removeObjectForKey:@"three"]
b)刪除多對(duì)鍵值對(duì):[dictM removeObjectsForKeys:@[@"one",@"two"]]
c)刪除所有鍵值對(duì):[dictM removeAllObjects];
3 修改:
a)修改整個(gè)字典: [dictM setDictionary:@{@"one":@"1",@"two":@"2",@"three":@"3"}]
b)修改鍵值對(duì): [dictM setObject:@"4" forKey:@"one"]
dictM[@“one”]=@“4” 簡(jiǎn)寫(xiě)形式```
```僅供木木學(xué)習(xí),以及有需要的伙伴們閱讀~可轉(zhuǎn)載,不可復(fù)制粘貼喲~```