NSNumber, Setting and Retrieving

15,972

Solution 1

You want -intValue, or one of its friends (-floatValue, -doubleValue, etc.). From the docs:

intValue Returns the receiver’s value as an int.

- (int)intValue

Return Value The receiver’s value as an int, converting it as necessary.

The code would be:

int varMoney2 = [testNum intValue];

Solution 2

NSNumber *testNum = [NSNumber numberWithInt:varMoney];
/* Then later... */
int newVarMoney = [testNum intValue];
Share:
15,972
Ethan Mick
Author by

Ethan Mick

I am a software engineer and entrepreneur. Hopefully I'll do something cool, so keep in touch.

Updated on June 14, 2022

Comments

  • Ethan Mick
    Ethan Mick almost 2 years

    I'm messing around with NSNumber for an iPhone app, and seeing what I can do with it. For most of my variables, I simple store them as "int" or "float" or whatnot. However, when I have to pass an object (Such as in a Dictionary) then I need them as an Object. I use NSNUmber. This is how I initialize the object.

    NSNumber *testNum = [NSNumber numberWithInt:varMoney];
    

    Where "varMoney" is an int I have declared earlier in the program. However, I have absolutely no idea how to get that number back...

    for example:

    varMoney2 = [NSNumber retrieve the variable...];
    

    How do I get the value back from the object and set it to a regular "int" again?

    Thanks!

    (Out of curiosity, is there a way to store "int" directly in an Objective-C dictionary without putting it in an NSNumber first?)