1.创建字典
//1.减方法创建
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"one",@"key1",@"two",@"key2",@"three",@"key3", nil];
//2.分别把key和value放到数组中(key和value相互对应)
NSArray *objectsArr = @[@"one",@"two",@"three"];
NSArray *keysArr = @[@"key1",@"key2",@"key3"];
NSDictionary *dict4 = [[NSDictionary alloc]initWithObjects:objectsArr forKeys:keysArr];.
//3.快速创建字典
NSDictionary *dict5 = @{@"key1": @"one",@"key2":@"two",@"key3":@"three",@"key4":@"two"};
//4.获取
//获取字典的键值对个数
NSUInteger cnt = [dict5 count];
//5.所有key,所有value
NSArray *keys = [dict5 allKeys];
NSArray *values = [dict5 allValues];
//6.遍历
//先取到所有的key,然后根据各个key依次去取对应的值
for (int i = 0; i < [keys count]; i++) {
NSString *value = [dict5 objectForKey:keys[i]];
NSLog(@"value = %@",value);
}
/*
[dict1]
[dict2]
[dict3]
*/
NSArray *list = @[@{@"title":@"1",@"a":@"a"},@{@"title":@"2",@"b":@"b"},@{@"title":@"1",@"c":@"c"},@{@"title":@"1",@"b":@"d"}];
NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
for (NSDictionary *dic in list) {
NSString *title = [dic objectForKey:@"title"];
if ([mutableDic.allKeys containsObject:title]) {
NSMutableArray *array = [mutableDic objectForKey:title];
[array addObject:dic];
[mutableDic setObject:array forKey:title];
}else{
NSMutableArray *array = [NSMutableArray array];
[array addObject:dic];
[mutableDic setValue:array forKey:[dic objectForKey:@"title"]];
}
}
/*
name1:{
[dict1]
[dict2]
[dict3]
}
name2:{
[dict4]
[dict5]
[dict6]
}
*/