字典:
1、字典是一個(gè)對象;(NSDictionary類創(chuàng)建)
2截酷、字典以鍵值對形式存儲信息涮拗;
3、 字典鍵值對: key(鍵) :一般是字符串對象迂苛, value(值):可以是任意對象;
4三热、key必須是唯一;
5灾部、value可以不唯一康铭;
特征:
1.字典一定是成對存在的 鍵值對
2.字典是無序集合 (不能通過下標(biāo)來獲取值)
3.通過key來獲取value (key一般都是字符串對象惯退,value可以是任意對象)
NSDictionary的創(chuàng)建(不可變赌髓,一旦創(chuàng)建,內(nèi)容就不能添加/刪除改動):
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) 通過鍵值對創(chuàng)建:
NSDictionary *dict4 = @{@"紅臉":@"關(guān)羽",@"黑臉":@"張飛"};
NSDictionary常用方法:
1 獲取鍵值對個(gè)數(shù):
NSInteger count = [dict count] / dict.count
2 通過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類型
8 從文件中讀取字典:
NSDictionary *readDict=[NSDictionary dictionaryWithContentsOfFile:@"/Users/qianfeng/desktop/dict.plist"]
NSMutableDictionary常用方法:
1 增加:
a)增加一組鍵值對:[dictM setObject:@"1" forKey:@"one"]
注:setObject: forKey 字典中存在key 修改當(dāng)前key的value值 字符中不存在key 增加一對鍵值對
b) 增加整個(gè)字典:[dictM addEntriesFromDictionary:@{@"two":@"2",@"three":@"3"}]
2 刪除:
a)刪除一組鍵值對(通過key值刪除):[dictM removeObjectForKey:@"three"]
b)刪除多對鍵值對:[dictM removeObjectsForKeys:@[@"one",@"two"]]
c)刪除所有鍵值對:[dictM removeAllObjects];
3 修改:
a)修改整個(gè)字典: [dictM setDictionary:@{@"one":@"1",@"two":@"2",@"three":@"3"}]
b)修改鍵值對: [dictM setObject:@"4" forKey:@"one"]
dictM[@“one”]=@“4” 簡寫形式```
```僅供木木學(xué)習(xí)催跪,以及有需要的伙伴們閱讀~可轉(zhuǎn)載锁蠕,不可復(fù)制粘貼喲~```