当我试图在应用程序处于for循环中时将NSMutableDictonary插入NSMutableArrey时,我遇到了一种非常奇怪的行为。
每个for-step构造NSMutableDict并添加到数组中。但它不起作用...当我在for循环后打印出数组时,数组中的每个NSMutableDictonary都是相同的 - 经过一些日志记录后,我看到每个for-step,数组中的所有dictionarys都被替换,并且添加了一个在最后...这是一个奇怪的行为,我不知道什么导致这... 如果我将currentID(见代码)添加到dictonary的数组中,最后看起来都很好...... 这是什么问题?
NSArray *relativeIAbnormality = [[NSArray alloc] init];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int q = 0; q < [measureData.list count]; q++) {
[tempDict removeAllObjects];
NSString *currentId = [[measureData.list objectAtIndex:q] valueForKey:@"id"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", currentId];
NSInteger count = [[lastMeasureData.list filteredArrayUsingPredicate:predicate] count];
if(count > 0){
// get the answer Value for the CURRENT measure
float theValue = 0;
theValue = [[[[measureData.list objectAtIndex:q] objectForKey:@"propertys"] valueForKey:@"answerValue"] floatValue];
theValue = theValue/100;
if(theValue > 10){
theValue = 10;
}else if (theValue < 0) {
theValue = 0;
}
// get the answer Value for the LAST measure
float theNewValue = 0;
theNewValue = [[[[[lastMeasureData.list filteredArrayUsingPredicate:predicate] objectAtIndex:0] objectForKey:@"propertys"] valueForKey:@"answerValue"] floatValue];
theNewValue = theNewValue/100;
if(theNewValue > 10){
theNewValue = 10;
}else if (theNewValue < 0) {
theNewValue = 0;
}
// gets the reltaive
theValue = theValue - theNewValue;
NSNumber *dif = [NSNumber numberWithFloat:theValue];
[tempDict setObject:currentId forKey:@"id"];
[tempDict setObject:dif forKey:@"dif"];
//NSLog(@"tempDict: %@", tempDict);
[tempArray addObject:tempDict];
//NSLog(@"tempArray: %@", tempArray);
}
}
//NSLog(@"full tempArray: %@", tempArray);
答案 0 :(得分:1)
您继续使用相同的tempDict实例。将你的temp-dict的alloc-init对移到循环中。
NSArray *relativeIAbnormality = [[NSArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int q = 0; q < [measureData.list count]; q++)
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
...
}