Passing NSInteger variable to NSMutableDictionary or NSMutableArray

Question:

 

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?

 

Answer:

NSInteger isn’t an object — it’s simply typecast to int on 32-bit or long on 64-bit. SinceNSDictionary 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"];

Leave a comment