How do you store "int" values in an NSMutableArray* or NSMutableDictionary*? Chronic problems with JSON data that come in as integers.

MikeN picture MikeN · Jan 21, 2011 · Viewed 14.6k times · Source

How do you store "int" values in an NSMutableArray or NSMutableDictionary? Chronic problems with JSON data that come in as integers.

Should I try to store these integers as NSNumber objects or just as strings that contain the integer?

How dangerous is it to do a "raw" (int) conversion on the pointers if I know the values will always be Natural Numbers (numbers>=0 including zero for null.)

The integers I'm always working with are Foreign Key Id's from a database.

Answer

theChrisKent picture theChrisKent · Jan 21, 2011

Use NSNumber like this:

int yourInt = 5;
[myMutableArray addObject:[NSNumber numberWithInt:yourInt]];

Or using modern Objective C syntax, you can use the following for expressions:

[myMutableArray addObject:@(2 + 3)];

Or for lone numbers:

[myMutableArray addObject:@5];