I encountered a very strange behavior when i m trying to insert a NSMutableDictonary into an NSMutableArrey while the app is in a for-loop.
The NSMutableDict is constructed every for-step and added to an array. but it doesnt work… when i print out the array after the for loop, every NSMutableDictonary in the array is the same – After some logging, i saw that every for-step, all dictionarys in the array gets replaced and one is added at the end… thats a strange behavior and i dont know whats causing this…
If i add the currentID (see code) to the array insted of the dictonary, in the end, all looks fine…
whats the problem here?
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);
You keep using the very same instance of tempDict. Move that alloc-init pair of your temp-dict inside the loop.