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

时间:2011-03-02 20:52:03

标签: 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(@“%@”,总计);导致EXEC BAD ACCESS错误。有没有明显的事我做错了。此外,如果我删除日志,则没有添加到totalIncomes中,在我的头文件中声明为NSNumber。谢谢。

6 个答案:

答案 0 :(得分:7)

这个怎么样:

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

答案 1 :(得分:1)

总计是一个int。使用NSLog(@"%d", total);

您应该做的另一件事是在开始时将总数初始化为0。在C(和Objective C)中,内在类型不会归零。这可能会影响您的总数。

int total = 0;

修改:其他一些答案建议使用%i代替。 %i和%d与字符串格式相同,%D也是如此。这是格式说明符的完整图表:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

答案 2 :(得分:0)

您正在使用'%@',这是用于字符串的格式。您需要使用'%i'作为整数。例如:

NSLog(@"%i", total);

答案 3 :(得分:0)

怎么样:

NSEnumerator *enumerator = [IncomesArray objectEnumerator];

int total = 0; 
Income *income;
while (income = [enumerator nextObject]) {
    total += [income intValue];
    NSLog(@"%d", total);    
}

self.totalIncomes = [NSNumber numberWithInt:total];
NSLog(@"%.2f", self.totalIncomes);

答案 4 :(得分:0)

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

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

再次感谢大家的帮助和快速反应。我的所有错误都是由于我没有充分考虑到始终使用正确数据类型的重要性。

答案 5 :(得分:0)

建议重写:

- (void)totalIncome:(NSMutableArray *)IncomesArray {
    float total = 0; //automatics might not be initialized
    for (Income *income in IncomesArray) //use fast enumeration
    {
        total += [[income value] floatValue];
        NSLog(@"%.2f", [[income value] floatValue]);
    }
    //hand an autoreleased object to your setter:
    self.totalIncomes = [NSNumber numberWithFloat:(float)total]; 
    NSLog(@"%.2f", [self.totalIncomes floatValue]);
}