Objective-c 问题:通过循环遍历数组来总计数组
我有这段代码,它接受来自核心数据的一系列收入对象。
- (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 错误。有什么明显的我做错了吗?另外,如果我删除日志,则不会将任何内容添加到在我的头文件中声明为 NSNumber 的totalIncomes 中。谢谢。
I have this code wich accepts an array of income objects from 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);
}
But the line NSLog(@"%@", total); causes an EXEC BAD ACCESS error. Is there something obvious I have done wrong. Also if I remove the log nothing is added to totalIncomes which is declared in my header file as a NSNumber. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这个怎么样:
How about this:
总计是一个整数。使用
NSLog(@"%d", Total);
您应该做的另一件事是从一开始就将您的总计初始化为 0。在 C(和 Objective C)中,内部类型不会为您清零。这可能会影响您的总数。
编辑:其他一些答案建议使用 %i 代替。 %i 和 %d 对于字符串格式化来说是等效的,%D 也是如此。以下是格式说明符的完整图表:
http: //developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
total is an int. use
NSLog(@"%d", total);
the other thing you should be doing is initializing your total to 0 at the outset. In C (and Objective C) intrinsic types aren't zeroed out for you. This is probably affecting your total.
Edit: some other answers suggest using %i instead. %i and %d are equivalent for string formatting, as is %D. Here's a complete chart of format specifiers:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
您正在使用
'%@'
这是用于字符串的格式。您需要使用'%i'
表示整数。例子:You are using
'%@'
which is the format used for strings. You need to use'%i'
for integers. Example:再次感谢大家的帮助和快速回复。我所有的错误都是由于我不了解始终使用正确数据类型的重要性。
Thanks again for everyones help and fast responses. All my errors were due to my lack of understnding of the importance of using the correct data types at all times.
怎么样:
How about:
建议重写:
A suggested rewrite: