NSMutableArray会覆盖最后一个对象

时间:2015-08-03 06:03:14

标签: objective-c

我在循环之外初始化了nsmutablearray和nsmutable dictinay,而且还覆盖了所有数组的最后一个对象

NSMutableDictionary *dictNew=[[NSMutableDictionary alloc]init];
NSMutableArray *newArr =[[NSMutableArray alloc]init];
//dictNew=[[NSMutableDictionary alloc]init];

for (int i=0; i<[[[contactsData valueForKey:@"firstName"] objectAtIndex:0] count]; i++)
{
    [dictNew setObject:[[[contactsData valueForKey:@"firstName"]objectAtIndex:0]objectAtIndex:i] forKey:@"firstName"]:
    [dictNew setObject:[[[contactsData valueForKey:@"lastName"]objectAtIndex:0]objectAtIndex:i] forKey:@"lastName"];
    [dictNew setObject:[[[contactsData valueForKey:@"phones"]objectAtIndex:0]objectAtIndex:i] forKey:@"phones"];
    NSLog(@"%@",dictNew);
    [newArr addObject:dictNew];
    NSLog(@"newarr %@",newArr);
}

1 个答案:

答案 0 :(得分:0)

您无法像这样重用dictNew。每次迭代都需要一个新实例。如你所知,你最终会一遍又一遍地向数组中添加相同的字典。

试试这个:

NSMutableArray *newArr = [[NSMutableArray alloc]init];
for (int i = 0; i < [[[contactsData valueForKey:@"firstName"] objectAtIndex:0] count]; i++) {
    NSMutableDictionary *dictNew=[[NSMutableDictionary alloc]init];
    [dictNew setObject:[[[contactsData valueForKey:@"firstName"]objectAtIndex:0]objectAtIndex:i] forKey:@"firstName"]:
    [dictNew setObject:[[[contactsData valueForKey:@"lastName"]objectAtIndex:0]objectAtIndex:i] forKey:@"lastName"];
    [dictNew setObject:[[[contactsData valueForKey:@"phones"]objectAtIndex:0]objectAtIndex:i] forKey:@"phones"];
    NSLog(@"%@",dictNew);
    [newArr addObject:dictNew];
    NSLog(@"newarr %@",newArr);
}

我还建议一些小的改进和清理:

NSMutableArray *newArr = [[NSMutableArray alloc] init];
NSArray *firstNames = [[contactsData valueForKey:@"firstName"] objectAtIndex:0];
for (NSInteger i = 0; i < firstNames.count; i++) {
    NSMutableDictionary *dictNew = [[NSMutableDictionary alloc] init];
    dictNew[@"firstName"] = firstNames[i];
    dictNew[@"lastName"] = [[[contactsData valueForKey:@"lastName"] objectAtIndex:0] objectAtIndex:i];
    dictNew[@"phones"] = [[[contactsData valueForKey:@"phones"] objectAtIndex:0] objectAtIndex:i];
    NSLog(@"dictNew = %@", dictNew);
    [newArr addObject:dictNew];
}
NSLog(@"newArr = %@", newArr);