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

5

8

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.

Darmstadt answered 21/1, 2011 at 22:17 Comment(0)
B
23

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];
Buffybuford answered 21/1, 2011 at 22:23 Comment(0)
V
4

Use NSNumber objects (e.g. using [NSNumber numberWithInt:value])

Vociferous answered 21/1, 2011 at 22:23 Comment(0)
G
2

You need to use NSNumber, as others have said, or use an NSString with the string representaton of the number. It really doesn't matter which, but the NSNumber will be more efficient.

You can't just throw in an int, let it be interpreted as a pointer, and then cast it back on the way out. The reason is that the object (that the int will be interpreted as a pointer to) will be sent the retain message when it is added to the array, and this will definately cause a crash since it will be an invalid pointer.

Giffer answered 21/1, 2011 at 22:28 Comment(0)
N
2

You can also use:

[myDict setObject:[NSNumber numberWithInt:anInteger] forKey:@"MyInteger"];
Naturalize answered 21/1, 2011 at 22:28 Comment(0)
H
0

You can also add value like this

NSMutableArray *values = [NSMutableArray alloc]init];

[values addObject:[NSNumber numberWithInt:23]];

Hellebore answered 10/1, 2014 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.