1.字典的基本类型
1.空字典
NSDictionary *dic =[NSDictionary dictionary];
2.一个键值对
NSDictionary *dic2 =[NSDictionary dictionaryWithObject:@"iphone" forKey:@"k1"];//k1是随便取
3.根据键来取对应的值
NSString *str = [dic2 objectForKey:@"k1"];
2.创建一个多键值对的字典
2.1 方法一
NSArray *keyArray =@[@"k1",@"k2",@"k3",@"k4"];
NSArray *valueArray =@[@"v1",@"v2",@"v3",@"v4"];
NSDictionary *dic3 =[[NSDictionary alloc]initWithObjects:valueArray forKeys:keyArray];
dic3={k1 = v1;k2 = v2;k3 = v3;k4 = v4;};
2.2 第二种(字典里面的key只能唯一,如果重复了,只保存第一个)
NSDictionary *dic4 =[NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];//先写value再写key...
dic4={key1 = value1; key2 = value2;}
2.3 第三种(字面量)(key在前,value在后)
NSDictionary *dic5 =@{@"k1":@"v1"};//中间是冒号
3.字典的遍历(allvalue和allkeys取全部的key和全部的value)
for (NSString *str in dic3.allValues)
{
NSLog(@"str = %@",str);//str = v4,str = v3,str = v2,str = v1
}
4.可变字典
NSMutableDictionary *mdic1 = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"iphone",@"k1",@"ipad",@"k2",@"iwatch",@"k3", nil];
- 在一个字典的后面追加一个字典
[mdic1 addEntriesFromDictionary:dic5];
- 添加一个新的键值对
[mdic1 setValue:@"imac" forKey:@"k"];
- 修改原有键值对
[mdic1 setValue:@"Pro" forKey:@"k4"];
- 删除键值对
[mdic1 removeObjectForKey:@"k"];
5.NSSet(集合)
会自动的过滤掉重复的数据
NSSet *set1= [[NSSet alloc]initWithObjects:@"iphone",@"iphone",@"apple", @"iphone",nil];
NSSet *set2= [[NSSet alloc]initWithObjects:@"iMac",@"iBook",@"pro",@"Air",@"apple", nil];
- 判断一个容器里面是否包含某个对象(containsObject)
if ([set1 containsObject:@"ipad"]){
NSLog(@"YES");
} else{
NSLog(@"NO");
}
- 判断两个集合是否有交集
if ([set1 intersectsSet:set2]){
NSLog(@"有交集");
}else {
NSLog(@"没有交集");
}
- 判断两个集合的内容是否一样
if ([set1 isEqualToSet:set2]) {
NSLog(@"yiyang");
} else{
NSLog(@"buyiyang");
}
- 判断一个集合是否为另外一个集合的子集
if ([set1 isSubsetOfSet:set2]){
NSLog(@"shiziji");
}else{
NSLog(@"bushiziji");
}