当应用程序处于for循环中时,我试图将NSMutableDictionary插入到NSMutabbleArrey中时,遇到了一个非常奇怪的行为。
NSMutableDict是在每个for步骤中构造的,并添加到数组中。但它不起作用。。。当我在for循环后打印出数组时,数组中的每个NSMutableDictionary都是相同的-经过一些日志记录,我看到每个for步骤,数组中所有的dictionary都会被替换,并在末尾添加一个。。。这是一种奇怪的行为,我不知道是什么原因造成的。。。如果我将currentID(参见代码)添加到dictionary的数组中,那么最终,一切看起来都很好。。。这里有什么问题?
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);
您一直在使用相同的tempDict实例。在循环中移动临时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];
...
}