Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant store int or double in dictionary

Tags:

objective-c

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?

like image 917
some_id Avatar asked May 26 '11 22:05

some_id


2 Answers

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.

like image 157
Kongress Avatar answered Nov 15 '22 17:11

Kongress


Try using an NSNumber:

[data setValue:[NSNumber numberWithDouble: longitude] forKey:@"longitude"];
like image 22
Cameron Avatar answered Nov 15 '22 19:11

Cameron