Search code examples
ioscore-datansnumber

Recalling a NSNumber on valueforkey


Im am trying to display a NSNumber in my detail view of my application using core data. Currently I can get it working with a string value however I am stumped when trying to recall a nsnumber. I get a [__NSCFNumber length] error which I understand to be because I need to convert the nsnumber to a string? How would I go about changing the following code to do so? weightkg is the entity attribute containing the nsnumber.

   [self.kgLabel setText:[self.device valueForKey:@"weightkg"]];

Thank you in advance.


Solution

  • You have little control over formatting if you just use stringValue for your NSNumber. Instead you should make sure to convert into the correct primitive data type and format as desired:

    kgLabel.text = [NSString stringWithFormat:@"%.0f kg", number.floatValue];
    // --> "23 kg"
    
    kgLabel.text = [NSString stringWithFormat:@"%.2f kg", number.floatValue];
    // --> "23.43 kg"