Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing NSInteger variable to NSMutableDictionary or NSMutableArray

Why does this not work:

NSInteger temp = 20;
[userSettingsFromFile setObject:temp forKey:@"aTemp"];

but this does:

[userSettingsFromFile setObject:@"someObject" forKey:@"aTemp"];

How can I use the NSInteger variable?

like image 809
4thSpace Avatar asked Aug 27 '09 07:08

4thSpace


3 Answers

NSInteger isn't an object -- it's simply typecast to int on 32-bit or long on 64-bit. Since NSDictionary can only store objects, you need to wrap the integer into an object before you can store it. Try this:

NSInteger temp = 20;
[userSettingsFromFile setObject:[NSNumber numberWithInteger:temp] 
                         forKey:@"aTemp"]; 
like image 177
Matt Ball Avatar answered Oct 25 '22 10:10

Matt Ball


In order to store numbers in collections, you have to wrap them up in an NSNumber instance.

double aDouble = 20.3d;
NSInteger anInt = 20;

NSNumber *aWrappedDouble = [NSNumber numberWithDouble:aDouble];
NSNumber *aWrappedInt = [NSNumber numberWithInteger:anInt];

NSArray *anArray = [NSArray arrayWithObjects:aWrappedDouble, aWrappedInt, nil];
like image 24
dreamlax Avatar answered Oct 25 '22 12:10

dreamlax


Whatever you pass through setObject has to be derived from NSObject. NSInteger is not, it's a simple int typedef. In your 2nd example you use NSString, which is derived from NSObject.

like image 44
ttvd Avatar answered Oct 25 '22 11:10

ttvd