JohnnyRedTruss
JohnnyRedTruss

Reputation: 259

NSDecimalNumber question for core data and iPhone

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!

Upvotes: 5

Views: 3316

Answers (2)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

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

Upvotes: 3

Jose Cherian
Jose Cherian

Reputation: 7707

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

Upvotes: 5

Related Questions