Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NSString not respond to selector longValue but does respond to longLongValue and intValue?

I am trying to get the long value of an NSString by calling longValue, but NSString doesn't respond to longValue. It, however, does respond to intValue and longLongValue.

Is this the intended behavior? If yes, why? I can't see a logical reason for it to respond to intValue and longLongValue, but not longValue.

I can add a category on NSString and add:

-(long)longValue{
    return (long)[self longLongValue];
}

This solves my problem. But I still don't understand why this not the default implementation.

like image 411
Can Poyrazoğlu Avatar asked Jan 02 '26 06:01

Can Poyrazoğlu


2 Answers

Edit 1:

This should answer you as to why we can't get a longValue from NSString Major 64-bit changes

First Answer:

Apple's documentation speaks of getting only the following Numeric types:

doubleValue
floatValue
intValue
integerValue
longLongValue
boolValue

Apple's doc on NSString

So Probably one of the Ways to get a longValue from a NSString Type is how you are doing it.

I am not sure that you will get the intended result as you are type casting to longValue.

However, the other possible way to get a longValue from NSString would be:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; long number = [[numberFormatter numberFromString:string] longValue];

like image 107
Basanth Avatar answered Jan 03 '26 23:01

Basanth


If you want 64-bit across all CPU architectures then you want long long or int64_t, which is catered for with:

[NSString longLongValue]
like image 32
trojanfoe Avatar answered Jan 03 '26 23:01

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!