【问题标题】:Extract a NSDictionary from a NSMutableArray从 NSMutableArray 中提取 NSDictionary
【发布时间】:2011-12-08 18:34:14
【问题描述】:

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

【问题讨论】:

  • 数组的内容怎么看?您正在使用 ++i 循环,这可能意味着第 0 个元素将被跳过,并且在进行最后一次迭代时,您将超出数组的范围。

标签: objective-c ios nsmutablearray nsdictionary sigabrt


【解决方案1】:

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

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

或:

for (NSDictionary* dictVar in shoppingListItems) {

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

【讨论】:

  • 好的。不知道这个。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多