NSDictionary
通过唯一的key找到对应的value,相当于java中的map
常见的创建NSDictionary的方法
//第一种创建方法,字典是不可变的,初始化之后不可添加删除元素
NSDictionary *dict=[NSDictionary dictionaryWithObject:@“v1”forKey:@“k1”];
//第二种创建方法,最常用
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:
@“v1”,@“k1”,
@“v2”,@“k2”,
@“v3”,@“k3”,
@“v4”,@“k4”,nil];
//第三种创建方法
NSArray *values=[NSArray arrayWithObjects:@“v1”,@“v2”,@“v3”,@“v4”,nil]; NSArray *keys=[NSArray arrayWithObjects:@“k1”,@“k2”,@“k3”,@“k4”,nil]; NSDictionary *dict=[NSDictionary dictionaryWithObjects:values forKeys:keys];
字典使用:
快速遍历:for(NSString *key in dict)
使用迭代器遍历字典:
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @“v1”,@“k1”, @“v2”,@“k2”, @“v3”,@“k3”, @“v4”,@“k4”,nil]; //获取迭代器 NSEnumerator *enumerator=[dict keyEnumerator]; id key =nil while(key=[enumerator nextObject]){ id value=[dict objectForKey:key]; }
使用block遍历字典:
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @“v1”,@“k1”, @“v2”,@“k2”, @“v3”,@“k3”, @“v4”,@“k4”,nil]; //使用block [dict enumerateKeysAndObjectsUsingBlock:^(id key,id value,BOOL *stop){ NSLog(@“%@%@“,key,value); }
NSDictionary的key排序
- -(NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
- -(NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr
- -(NSArray *)keysSortedByValueUsingSelector:(SEL)comparator
用法参照NSArray的排序
NSMutableDictionary(可变字典)
//创建一个空的字典 NSMutableDictionary *dict=[NSMutableDictionary dictionary]; //创建两个字符串对象 NSString *str1=[NSString stringWithString:@“stu.gx203.1”]; NSString *str2=[NSString stringWithString:@“stu.gx203.2”]; //将字符串对象添加到可变字典中 [dict addObject:str1 forKey:@“k1”]; [dict addObject:str2 forKey:@“k2”];
添加其他字典到当前字典
NSDictionary *otherdict=[NSDictionary dictionaryWithObject:@“str.gx203.3” forKey:@“k3”]; [dict addEntriesFromDictionary:otherdict];
添加删除操作参考NSMutableArray