How to store int values ​​in NSMutableArray * or NSMutableDictionary *? Chronic problems with JSON data that are integers.

How to store "int" values ​​in NSMutableArray or NSMutableDictionary ? Chronic problems with JSON data that are integers.

Should I try to save these integers as NSNumber objects or as strings containing an integer?

How dangerous is it to do raw conversion of pointers if I know that the values ​​will always be natural numbers (numbers> = 0, including zero for zero.)

The integers that I always work with are the foreign key identifier from the database.

+7
source share
5 answers

Use NSNumber, for example:

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

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

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

Or for single numbers:

 [myMutableArray addObject:@5]; 
+22
source

Use NSNumber objects (for example, using [NSNumber numberWithInt:value] )

+4
source

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

You cannot just throw an int , let it be interpreted as a pointer, and then drop it on the output. The reason is that an object (which int will be interpreted as a pointer to) will receive a retain message when it is added to the array, and this will certainly fail because it will be an invalid pointer.

+2
source

You can also use:

 [myDict setObject:[NSNumber numberWithInt:anInteger] forKey:@"MyInteger"]; 
+2
source

You can also add a value like this

NSMutableArray * values ​​= [NSMutableArray alloc] init];

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

0
source

All Articles