开发者

Trying to loop through an array and total up NSDecimalNumbers

I have the following code:

- (NSDecimalNumber *)totalBudgetItems {
    NSEnumerator *e = [self.defaultBudgetItemsArray objectEnumerator];
    id object;
    while (object = [e nextObject]) {
        NSDecimalNumber *numberToAdd = [[NSDecimalNumber alloc] initWithDecimal:[[object objectForKey:@"actualValue"] decimalValue]];
        currentTotal = [currentTotal decimalNumberByAdding:numberToAdd];
        [numberToAdd release];
    }
    return currentTotal;
}

It crashes on the line where I alloc numberToAdd. In the debugger, I open up "Locals", followed by "numberToAdd". "currentTotal" is in red with "invalid CFStringRef" in it. Otherwise I'm not sure what is happening.

In my .h I have:

NSDecimalNumber *currentTotal;

and

@property (nonatomic, retain) NSDecimalNumber *currentTotal;

The console also says:

2010-10-06 13:32:07.018 App[9433:307] -[NSCFString objectForKey:]: unrecognized selector sent to instance 0x16c6f0
2010-10-06 13:32:07.030 App[9433:307] *** Terminating app due to uncaugh开发者_StackOverflowt exception 'NSInvalidArgumentException', reason: '-[NSCFString objectForKey:]: unrecognized selector sent to instance 0x16c6f0'

Any thoughts?

Thanks!

-Max


The problem is that you send a -decimalValue to a object that returns an integral representation. However, initWithDecimal: expects an object, thus sends a message and crashes, since there is almost certainly no object at that address.

This code should work:

currentTotal = [currentTotal decimalNumberByAdding: [object objectForKey:@"actualValue"]];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜