gpt4 book ai didi

objective-c - 从 NSMutableArray 中提取 NSDictionary

转载 作者:行者123 更新时间:2023-11-28 23:12:34 25 4
gpt4 key购买 nike

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

最佳答案

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

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

或:

for (NSDictionary* dictVar in shoppingListItems) {

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

关于objective-c - 从 NSMutableArray 中提取 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7785264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com