从NSMutableArray中提取NSDictionary

时间:2011-10-16 15:27:28

标签: objective-c ios nsmutablearray nsdictionary sigabrt

我需要从NSMutableArray中提取NSDictionary,并从该字典中提取对象。 代码应该很简单,但我在NSDictionary声明中一直有一个SIGABRT错误。

-(void)calcolaConto {
        conto = [[NSNumber alloc] initWithDouble:0];
    for (int i=0; [shoppingListItems count]; ++i) {
        NSDictionary *dictVar = (NSDictionary *) [shoppingListItems objectAtIndex:i]; //<-- SIGABRT
        NSNumber *IO = (NSNumber *) [dictVar objectForKey:@"incout"];
        NSNumber *priceValue = (NSNumber *) [dictVar objectForKey:@"price"];
        if ([IO isEqualToNumber:[NSNumber numberWithInt:0]]) {
            conto = [NSNumber numberWithDouble:([conto doubleValue] + [priceValue doubleValue])];
        } else if ([IO isEqualToNumber:[NSNumber numberWithInt:1]]) {
            conto = [NSNumber numberWithDouble:([conto doubleValue] - [priceValue doubleValue])];
        }
        NSLog(@"Valore %@", conto);
    }
}

“shoppingListItems”以这种方式创建:

    NSMutableDictionary *rowDict = [[NSMutableDictionary alloc] initWithCapacity:6];
    [rowDict setObject:primaryKeyValue forKey: ID];
    [rowDict setObject:itemValue forKey: ITEM];
    [rowDict setObject:priceValue forKey: PRICE];
    [rowDict setObject:groupValue forKey: GROUP_ID];
    [rowDict setObject:incOut forKey:INC_OUT];
    [rowDict setObject:dateValue forKey: DATE_ADDED];
    [shoppingListItems addObject: rowDict];

1 个答案:

答案 0 :(得分:2)

问题是你的循环永远不会停止。你应该使用:

for (NSUInteger i = 0; i < [shoppingListItems count]; i++) {

或:

for (NSDictionary* dictVar in shoppingListItems) {

这样您就不会尝试访问超出范围的元素。在你的 当前循环i将递增,直到达到[shoppingListItems count] 这超出了数组的末尾,因此objectAtIndex将抛出异常。