I have this bit of Objective C code, where I am casting a NSString
to an int
:
NSString *a=@"123abc";
NSInteger b=(int) a;
NSLog(@"b: %d",b);
And the NSLog
produces this output:
b: 18396
Can anyone explain to me why this is happening?
I was under the impression type casting a string to an integer would get the numerical value from the string.
To get the numerical value use :
or for
NSInteger
:Or with Objective-C literals syntax:
When you cast an object to an integer you will get the pointer to the memory address. You can call to
[a integerValue]
to get the integer value of the string.Also when casting it is better to use
NSInteger
instate ofint
. Because when using a 64 bit operating system aNSInteger
will be 64 bit.You've got integer value of pointer to
NSString
object there. To parse string to integer you should do: