How to get double value from dictionary?
I'm trying to get a double value from a dictionary. How can I accomplish开发者_开发知识库 this in objective-c?
Dave's response to your previous question holds true for this, as well. To store a double value in an NSDictionary, you will need to box it in an NSNumber.
To set a double value in the dictionary, you'd use code like the following:
[someDict setObject:[NSNumber numberWithDouble:yourDouble] forKey:@"yourDouble"];
and read it back using the following:
double isTrue = [[someDict objectForKey:@"yourDouble"] doubleValue];
Brad Larson's response is exactly right. To elaborate on this a little more, you have to explicitly "wrap up" non-object number types (e.g., int
, unsigned int
, double
, float
, BOOL
, etc.) into NSNumber
when working with anything that expects an object.
On the other hand, however, some mechanisms in Objective-C, like Key-Value Coding (KVC), will automatically do this wrapping for you.
For example, if you have a @property
of type int
called intProperty
, and you call NSObject (NSKeyValueCoding)
's valueForKey:
method like [ someObject valueForKey:@"intProperty" ]
, the return result will be an NSNumber *
, NOT an int
.
Frankly, I don't care for having to switch between dealing with object and non-object types (especially struct
s and enum
s!) in Objective-C. I'd rather everything be treated as an object, but maybe that's just me. :)
精彩评论