一、NSDictionary
字典的两种创建方法
1 NSDictionary *dic1 =[[NSDictionary alloc]init];
2 // 或:
3 NSDictionary *dic2 =[NSDictionary dictionary];
1 // 字典添加数据 2 NSDictionary *dics1 =[[NSDictionary alloc]initWithObjects:[@"1,2,3" componentsSeparatedByString:@","] forKeys:[@"a,b,c" componentsSeparatedByString:@","]]; //用定的分割符把两个数组分割,分别的到对应的 (键)key 和 (值)value 3 4 NSDictionary *dics2 =[[NSDictionary alloc]initWithObjectsAndKeys:@"key1",@"aaa", @"key2",@"bbb",@"key3",@"ccc",nil]; 5 // 每两个为一对,分别对应(键)key 和 (值)value 6 7 NSDictionary *dic3 =@{@"key1":@"aaa",// 每两个为一对,分别对应(键)key 和 (值)value 8 @"key2":@"bbb", 9 @"key3":@"ccc"};
二、NSMutableDictionary
1 // 可变字典添加数据 2 NSMutableDictionary *Mdic1 =[[NSMutableDictionary alloc]init]; 3 // 或: 4 NSMutableDictionary *Mdic2 =[NSMutableDictionary dictionary]; 5 Mdic2[@"aaa"] =@"123"; //注意:如果已经有对应的键和值,则会改变对的的值,如果没有就会添加新的键和值 6 // 添加数据 7 [Mdic2 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { 8 NSLog(@"%@---%@",key,obj); //结果:aaa---123 9 10 }];