When trying to store a double or an int in a dictionary I get an error
error: Semantic Issue: Sending 'double' to parameter of incompatible type 'id'
I have the following code
[data setValue:longitude forKey:@"longitude"];
longitude is a double.
How should I store this? should I just create a pointer to an int or a double?
As the other posts have stated, you need to use an NSNumber
to wrap your double value in an object. The reason for this is that all the Cocoa foundation collection classes are designed to work with objects rather than primitive values. As you suggested, with some work you could in fact pass a pointer to a double value (I think, if you managed to cast it as an id
type pointer), but as soon as your method finished and the double went out of scope it would be released and your pointer would now be pointing to garbage. With an object, the collection (NSDictionary
, in this case) will retain your object when it's added and release it when it's removed or the collection is dealloc
'ed, ensuring your value will survive until you don't need it anymore.
I would do it as follows:NSNumber *tempNumber = [[NSNumber alloc] initWithDouble:longitude];
[data setValue:tempNumber forKey:@"longitude"];
[tempNumber release];
Which will leave your NSNumber object with only a +1 reference count (the dictionary retaining it) and no autoreleases
The other suggested method of doing:[data setValue:[NSNumber numberWithDouble: longitude] forKey:@"longitude"];
will also work fine but your object will end up with +1 reference count an an autorelease from the numberWithDouble method. When possible I try to avoid autoreleases, but the code is more concise. YMMV.
Try using an NSNumber:
[data setValue:[NSNumber numberWithDouble: longitude] forKey:@"longitude"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With