iOS: странное поведение при вставке NSDictonary в NSArray в цикле for (двойные записи) - PullRequest
0 голосов
/ 25 марта 2012

Я столкнулся с очень странным поведением, когда я пытался вставить NSMutableDictonary в NSMutableArrey, пока приложение находится в цикле for.

NSMutableDict создается каждый шаг for и добавляется в массив.но это не работает ... когда я распечатываю массив после цикла for, все NSMutableDictonary в массиве одинаковы - после некоторой регистрации я увидел, что каждый шаг for, все словари в массиве заменяются, и один добавляетсяв конце ... это странное поведение, и я не знаю, что вызвало это ... Если я добавлю currentID (см. код) к массиву, установленному из диктонары, в конце все выглядит хорошо ... в чем проблемаздесь?

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);

1 Ответ

1 голос
/ 25 марта 2012

Вы продолжаете использовать один и тот же экземпляр tempDict.Переместите эту пару alloc-init вашего temp-dict в цикл.

NSArray *relativeIAbnormality = [[NSArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int q = 0; q < [measureData.list count]; q++) 
{
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
    ...
}
...