Objective-c 问题通过循环遍历数组来求和

标签 objective-c ios core-data nsarray int

我有这段代码,它接受来自 Core Data 的收入对象数组。

- (void)totalIncome:(NSMutableArray *)IncomesArray {
    int i;
    int total;
    for (i = 0; i < [IncomesArray count]; ++i)
    {
        Income *income = [IncomesArray objectAtIndex:i];

        total += (int)[income value];
        NSLog(@"%@", total);
    }
    self.totalIncomes = [[NSNumber alloc] initWithInt:(int)total];
    NSLog(@"%.2f", self.totalIncomes);
}

但是行 NSLog(@"%@", total);导致 EXEC BAD ACCESS 错误。有什么明显的我做错了吗?此外,如果我删除日志,则不会向 totalIncomes 添加任何内容,totalIncomes 在我的头文件中声明为 NSNumber。谢谢。

最佳答案

这个怎么样:

- (void)totalIncome:(NSMutableArray *)IncomesArray {
    NSNumber *total = [IncomesArray valueForKeyPath:@"@sum.value"];
    NSLog(@"total: %@", total);
}

关于Objective-c 问题通过循环遍历数组来求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5173287/

相关文章:

objective-c - 你什么时候想在辅助线程上运行 NSURLConnection ?

ios - UIBarbuttonItem 关闭 UIVIewcontroller

ios - Objective-C 中类似 Photoshop 的曲线工具

ios - 核心数据目录(树)结构

objective-c - RestKit - fetchFromDataStore(缓存)问题

objective-c - 为什么在 Objective-C 库中使用 ARC 时会出现警告?

objective-c - 如何测试Cocoa应用程序和iOS应用程序之间的iCloud同步

iphone - UIImagePickerController 在不要求 "use"确认的情况下拍照

ios - 使用 NSPredicate 按 boolean 属性过滤 NSManagedObjects

objective-c - 使用@synthesize 覆盖 Objective-C 中的属性访问器名称