0

我需要从 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];
4

1 回答 1

2

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

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

或者:

for (NSDictionary* dictVar in shoppingListItems) {

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

于 2011-10-16T15:34:33.223 回答