Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get double value from dictionary?

Tags:

objective-c

I'm trying to get a double value from a dictionary. How can I accomplish this in objective-c?

like image 808
LB. Avatar asked Dec 18 '22 03:12

LB.


2 Answers

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];
like image 141
Brad Larson Avatar answered Dec 27 '22 01:12

Brad Larson


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 structs and enums!) in Objective-C. I'd rather everything be treated as an object, but maybe that's just me. :)

like image 39
CIFilter Avatar answered Dec 27 '22 02:12

CIFilter