//NSMutableDictionary 与 NSMutableArray注意的地方 -(void)testDic { //初始化 NSMutableDictionary *dic = [[NSMutableDictionary alloc]init]; NSMutableDictionary *dic1 = [[NSMutableDictionary alloc]init]; NSMutableArray *arr = [[NSMutableArray alloc]init]; //在里面添加数据 [dic setObject:@"qingjoin" forKey:@"Name"]; [dic setObject:@"100" forKey:@"Id"]; [dic1 setObject:@"cook" forKey:@"Name"]; [dic1 setObject:@"99" forKey:@"Id"]; //再把两个 NSMutableDictionary 里的数据添加到 NSMutableArray [arr addObject:dic]; [arr addObject:dic1]; //这时NSMutableArray里就有了两组数据。 //初始化 //NSMutableDictionary *saveDic = [[NSMutableDictionary alloc]init]; /*外面初始化会导致saveDic的值只可能有一组*/ NSMutableArray *saveArr = [[NSMutableArray alloc]init]; int count = [arr count]; //为2 for(int i = 0; i<count; i++) { if([[[arr objectAtIndex:i]objectForKey:@"Name"]length]>0) { /*这个地方要注意。saveDic的初始化只能在这里面。如果是在外面那么saveArr的值就只能是一后面得到的saveDic的值只有一组*/ NSMutableDictionary *saveDic = [[NSMutableDictionary alloc]init]; //把从arr里的两组数据分别给saveDic [saveDic setObject:[[arr objectAtIndex:i]objectForKey:@"Name"]forKey:@"Name"]; [saveDic setObject:[[arr objectAtIndex:i]objectForKey:@"Id"] forKey:@"Id"]; [saveArr addObject:saveDic]; } } NSLog(@"saveArr:%@",[[saveArr objectAtIndex:0]objectForKey:@"Name"]); //name 打印出来为qingjoin NSLog(@"saveArr:%@",[[saveArr objectAtIndex:1]objectForKey:@"Name"]); //name 打印出来为cook //如果saveDic 初始化放在外面 。那么name 打印出来为都为cook }
NSMutableDictionary 与 NSMutableArray注意的地方
最新推荐文章于 2021-05-09 17:25:11 发布