从NSMutableArray中提取一个NSDictionary



我需要从NSMutableArray中提取一个NSDictionary,并从那个dictionary中提取一个对象。代码应该很简单,但是我在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];

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

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

或:

for (NSDictionary* dictVar in shoppingListItems) {

,这样您就不会尝试访问超出边界的元素。在你的当前循环i将递增,直到达到[shoppinglisttitems count]

最新更新