开发者

Extract a NSDictionary from a NSMutableArray

I need to extract a NSDictionary from a NSMutableArray, and extract an object from that dictionary. The code should be quite easy, but I keep having a SIGABRT error on the NSDictionary declaration.

-(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 ob开发者_StackOverflowjectForKey:@"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" is created in this way:

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


The problem is that your loop never stops. You should use:

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

or:

for (NSDictionary* dictVar in shoppingListItems) {

so that you do not try to access an element that is out of bounds. In your current loop i will be incremented until it reaches [shoppingListItems count] which is beyond the end of the array, so objectAtIndex will throw an exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜