可变字典(NSDictionary)与不可变字典(NSMutableDictionary)

字典 :key与value组合成的键值对的集合
特点: 无序的 ,存的都是对象类型

NSDictionary的创建

1.NSDictionary *dic=[NSDictionary dictionary]

2.NSDictionary *dic=[NSDictionary dictionaryWithObject:@"展昭" forKey:@"包拯"];

3.NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"展昭",@"包拯", nil];//value 在前  key在后

4.NSDictionary *dic3=[NSDictionary dictionaryWithDictionary:dic];

6.NSDictionary *dic4=@{@"name":@"展昭",@"hobby":@"打架"};//key在前 value在后

通过key访问字典对应值(通过key访问value,对于返回的类型不能确定,所以用id)

 id name= [dic4 objectForKey:@"name"];
        NSLog(@"%@",name);

字典键值对的个数

NSUInteger count=dic4.count;

访问字典中所有的key value(返回的是数组)

NSArray *array=[dic4 allKeys];
NSArray *array2=dic4.allValues;

NSMutableDictionary的创建

1.NSMutableDictionary *mdic=[NSMutableDictionary dictionary];

2.NSMutableDictionary *mdic2=[NSMutableDictionary dictionaryWithObject:@"xiaoming" forKey:@"name"];

3. NSMutableDictionary *mdic3=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Joy",@"name",@"lol",@"hobby", nil];//value在前  key在后

4. NSMutableDictionary *mdic4=[NSMutableDictionary dictionaryWithDictionary:mdic3];

5. NSMutableDictionary *mdic5=[NSMutableDictionary dictionaryWithCapacity:100];

6. NSMutableDictionary *mdic6=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Rick",@"name",@25,@"age",@"GZ",@"address", nil];

通过key删除指定的value

[mdic6 removeObjectForKey:@"name"];

删除所有的键值对

[mdic6 removeAllObjects];

增加键值对

[mdic6 setValue:@"Joy" forKey:@"name"];
注意:
1.增加一个相同的key时,会覆盖掉之前的值
[mdic6 setValue:@"Rick" forKey:@"name"];

2.在创建字典时,关键字如果重复了,会覆盖掉之前的值

通过关键字改值

mdic6[@"name"]=@"yy";

你可能感兴趣的:(可变字典(NSDictionary)与不可变字典(NSMutableDictionary))