Search code examples
iphonecore-datansdecimalnumber

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!


Solution

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