不可变字典
一 创建字典对象
1) NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@100,@"老 谈",@"two",@"2",@"three",@"3", nil];
2) NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:@[@"qf",@"1603"] forKeys:@[@"name",@"className"]];
3)NSDictionary *dic3 = @{@"1":@"one",@"2":@"two",@"3":@"three"}; 【重点】
二 字典的常用方法
1)通过key取得对应的value 【重点】
NSNumber *nm = [dic1 objectForKey:@"老谈"];
int a = [nm intValue];
NSLog(@"a = %d",a);
//方法嵌套使用
NSLog(@"%d",[[dic1 objectForKey:@"老谈"] intValue]);
新语法 NSString *str = dic3[@"3"]; //取出键为3的值 【新语法】
2)返回所有的key
NSArray *keys = [dic3 allKeys];
3)返回所有的value
NSArray *values = [dic3 allValues];
4)返回键值对的个数
NSLog(@"count = %ld", dic3.count);
5)字典的遍历 【***重中之重***】
//快速枚举遍历字典
//in的右边所遍历的那个字典对象
//in的左边字典中key的类型 key要有意义,所以一般都用字符串来写
for (NSString *keyStr in dic1) {
NSLog(@"key = %@ ---- value = %@",keyStr,dic1[keyStr]);
}
可变字典
一 创建可变字典
1)创建一个空的可变字典 【***常见】
NSMutableDictionary *mDict1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mDict2 = [NSMutableDictionary dictionary];
2)创建带多个键值对的可变字典
NSMutableDictionary *mDict3 = [[NSMutableDictionary allo] initWithObjectsAndKeys:, nil];
NSMutableDictionary *mDict4 = [NSMutableDictionary dictionaryWithObjectsAndKeys:, nil];
3)把一个不可变字典转换成可变字典 【***常见】
NSDictionary *dict = @{@"1":@"one",@"2":@"two",@"3":@"three"};
NSMutableDictionary *mDict5 = [[NSMutableDictionary alloc] initWithDictionary:dict];
NSMutableDictionary *mDict6 = [NSMutableDictionary dictionaryWithDictionary:dict];
二 添加键值对
[mDict6 setObject:@"four" forKey:@"4"];
NSLog(@"mDict6 = %@", mDict6);
[mDict6 setObject:@"A" forKey:@"1"];
NSLog(@"mDict6 = %@", mDict6);
三 删除键值对
//1.根据key删除对应的键值对
[mDict6 removeObjectForKey:@"2"];
NSLog(@"mDict6 = %@", mDict6);
//2.删除多个键值对
[mDict6 removeObjectsForKeys:@[@"1",@"4"]]; //一次删除多个用数组
NSLog(@"mDict6 = %@", mDict6);
//3.删除所有的键值对
[mDict6 removeAllObjects];
NSLog(@"mDict6 = %@", mDict6);
四 重置键值对
//1.重置键值对
[mDict6 setDictionary:@{@"1":@"A",@"2":@"B",@"3":@"C"}];
NSLog(@"mDict6 = %@", mDict6);