NSDecimalNumber question for core data and iPhone

3.3k Views Asked by At

I'm fairly new to core data and iphone programming. Maybe this is an obvious answer, so if anyone can point me to a tutorial or other resource, it's greatly appreciated! I have a core data entity that is a decimal type as it's dealing with currency, and everything I have read says to use NSDecimalNumber when dealing with currency. That being said, I cannot for the life of me figure out how to set the value when inserting a new object. Here is what I have

NSManagedObjectContext *moc = [self.fetchedResultsController managedObjectContext];
Envelope *envelope = [NSEntityDescription insertNewObjectForEntityForName:@"Envelope"
                                                inManagedObjectContext:moc];
[envelope setValue:@"Envelope 1" forKey:@"name"];
NSDecimalNumber *budgetNumber = [NSDecimalNumber decimalNumberWithDecimal:1.00];
[envelope setValue:budgetNumber forKey:@"budget"];

What am I doing wrong here? thanks in advance!

2

There are 2 best solutions below

11
On BEST ANSWER

Try this:

NSDecimalNumber *budgetNumber = [NSDecimalNumber decimalNumberWithString:@"1.00"];

PS: Adding solution for the second issue stated in comments

(void)configureCell:(UITableViewCell *)cell withEnvelope:(NSManagedObject *)model{ 
     UILabel *envelopeNameLabel = (UILabel *) [cell viewWithTag:1];

     envelopeNameLabel.text = [model valueForKey:@"name"]; 

     UILabel *envelopeBudgetLabel = (UILabel *) [cell viewWithTag:2];
     envelopeBudgetLabel.text = [model valueForKey:@"budget"];
     }

'NSInvalidArgumentException', reason: '-[NSDecimalNumber isEqualToString:]: unrecognized selector sent to instance 0x653fc80' .

This issue is caused by assigning a decimal number to a string. You have to get the string representation before assigning it to the label. Something like this:

envelopeBudgetLabel.text = [[model valueForKey:@"budget"] description];
4
On

NSDecimalNumber is very precise and should be constructed precisely:

NSDecimalNumber *budgetNumber = [NSDecimalNumber decimalNumberWithMantissa:1 exponent:0 isNegative:NO];

Will give you a NSDecimalNumber representation of 1. If you wanted a NSDecimalNumber representation of -12.345 then it would be constructed:

NSDecimalNumber *budgetNumber = [NSDecimalNumber decimalNumberWithMantissa:12345 exponent:-3 isNegative:YES];