字典是一个无序的集合,也可称之为键值对。与数组不同的是字典可以通过特定的key快速查找到想要的值,而不用遍历字典。所以一个唯一的key只能对应一个值,而多个key可以对应同一个值。字典分为不可变字典(NSDictionary)和可变字典(NSMutableDictionary)。NSMutableDictionary继承自NSDictionary。自本篇文章只介绍NSMutableDictionary的简单用法。
1、NSMutableDictionary的创建
1>初始化创建字典
NSMutableDictionary* mdict1=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3", nil]; //实例方法
NSMutableDictionary* mdict2=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3", nil]; //类方法
2>通过键值数组创建字典
NSMutableDictionary* mdict3=[[NSMutableDictionary alloc]initWithObjects:@[@"v1",@"v2",@"v3"] forKeys:@[@"k1",@"k2",@"k3"]]; //实例方法
NSMutableDictionary* mdict4=[NSMutableDictionary dictionaryWithObjects:@[@"v1",@"v2",@"v3"] forKeys:@[@"k1",@"k2",@"k3"]];//类方法
3>通过已有的字典创建
NSMutableDictionary* mdict5=[[NSMutableDictionary alloc]initWithDictionary:mdict1];//实例方法
NSMutableDictionary* mdict6=[NSMutableDictionary dictionaryWithDictionary:mdict1];//类方法
注意 可变字典不能用如下方式创建
NSMutableDictionary* mdict7=@{@"k1":@"v1", @"k2":@"v2", @"k3":@"v3"}; //错误写法
2、NSMutableDictionary 添加键值对
1>setObject: forKey: 向字典中添加一组数据
NSMutableDictionary* mdict1=[[NSMutableDictionary alloc]init];
[mdict1 setObject:@"value1" forKey:@"key1"];//插入数据
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
2>addEntriesFromDictionary:将一个字典中的所有元素添加到另一个字典
[mdict1 addEntriesFromDictionary:@{@"k1":@"v1", @"k2":@"v2"}];
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
打印结果
3、删除NSMutableDictionary中的键值对
NSMutableDictionary *mdict1=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3", nil];
//通过key 删除字典中对应的键值对
[mdict1 removeObjectForKey:@"k1"];
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
//通过多个key 删除字典中对应的多个键值对
[mdict1 removeObjectsForKeys:@[@"k2",@"k3"]];
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
//重置字典
[mdict1 setDictionary:@{@"1":@"one", @"2":@"two"}];
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
//删除所有键值对
[mdict1 removeAllObjects];
NSLog(@"可变字典mdict1[键值对数量:%lu],%@" ,[mdict1 count], mdict1);
打印结果