开发者

Cant store int or double in dictionary

开发者 https://www.devze.com 2023-03-08 12:46 出处:网络
When tr开发者_开发百科ying 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\'

When tr开发者_开发百科ying 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"];


A dictionary wants an NSObject, not a number or a pointer. However it's easy to create an object containing a number:

NSNumber *mylongitudeObject = [NSNumber numberWithDouble:myLongitude];

which you can thence store in an NSDictionary.

Under the hood: mylongitudeObject will actually be a pointer to an opaque structure containing a copy of your number; but the structure also contains information so that the Objective C runtime knows what it can do with this object, such as how to copy it into a dictionary, etc.


You must use an NSNumber object instead. Try declaring longitude as follows

NSNumber longitude = [NSNumber numberWithDouble:myLongitude]


With the newer version of the compiler, you can use the Objective-C literal syntax to create a NSNumber from a variable of type double:

double longitude = 2.0;
dict[@"longitude"] = @(longitude);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号