NSArray changes the type of NSNumber

I want to store NSNumber as a double in NSArray. So I tried this:

NSArray *diamArray = [[NSArray alloc] initWithObjects:
                     [NSNumber numberWithDouble:1.0],
                     [NSNumber numberWithDouble:1.2],
                     nil];

      

And then I ask Xcode to show the diamArray:

NSLog(@"%@", diamArray);

      

And here's the result:

[8873:1153347] (
    1,
    "1.2"
)

      

So we can see that both numbers are not treated the same way. This is a problem for me as these values ​​are useful when changing their type. Specifically, in the array debug table, I see the decimal number (1.2) as "double", but the value 1.0 is shown as "null".

How do I make an array treat 1.0 as a double?

+3


source to share


3 answers


It is difficult to decipher data types from NSLog as it tries to display usable information. In this case 1.0 is exactly one, so it truncates that value so that it is Int. I almost guarantee that if you have to pull an element out of the array and render it objCType, you will find it is double:

NSLog("%@: %s", diamArray[0], [diamArray[0] objCType]);

      



Another thing to consider is that values ​​can be fetched from NSNumber, so even if it stores 1.0 as an integer value, you can still extract it as a double:

[diamArray[0] doubleValue]

      

+6


source


NSNumber - class cluster ... You shouldn't worry about how it stores information, but instead, you should mainly care about how you retrieve that information.

To get your double back , you only need to do:

double myDouble = [dimArray[0] doubleValue];

      



but there is also:

[dimArray[0] intValue];
[dimArray[0] integerValue];
[dimArray[0] unsignedIntegerValue];
[dimArray[0] floatValue];
...

      

+2


source


Thanks for your information and suggestions.

I find out it has to do with locale. My default locale is fr_FR and then I tried this:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[f setLocale:usLocale];
 NSArray *pasArray = [[NSArray alloc] initWithObjects:
                     [f numberFromString:[[NSNumber numberWithDouble:1.0] stringValue]],
                     [f numberFromString:[[NSNumber numberWithDouble:0.25] stringValue]],
nil];

      

and works as expected. My guess is that due to locale differences, the dot is misinterpreted. But I think it is not very clean for this.

I've come to the conclusion that David Berry is right: I don't have to worry about the display, and rather ask for the format I need when I need it.

Thanks again for helping me understand why this is not a problem.

0


source







All Articles