Objective C - Type Casting From NSString to Int

China☆狼群 提交于 2019-12-22 02:05:13

问题


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.


回答1:


You've got integer value of pointer to NSString object there. To parse string to integer you should do:

NSString *a = @"123abc";
NSInteger b = [a integerValue];



回答2:


To get the numerical value use :

int val = [stringObj intValue];

or for NSInteger :

NSInteger val = [stringObj integerValue];



回答3:


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 of int. Because when using a 64 bit operating system a NSInteger will be 64 bit.




回答4:


Or with Objective-C literals syntax:

@([a intValue]);


来源:https://stackoverflow.com/questions/13046047/objective-c-type-casting-from-nsstring-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!