开发者

Objective-c problem totalling an array by looping through it

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];

   开发者_JS百科     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.


How about this:

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


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.

int total = 0;

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


You are using '%@' which is the format used for strings. You need to use '%i' for integers. Example:

NSLog(@"%i", total);


- (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]);
}

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:

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);


A suggested rewrite:

- (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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜