How to convert an NSString to an unsigned int in Cocoa?

六眼飞鱼酱① 提交于 2020-01-01 05:08:50

问题


My application gets handed an NSString containing an unsigned int. NSString doesn't have an [myString unsignedIntegerValue]; method. I'd like to be able to take the value out of the string without mangling it, and then place it inside an NSNumber. I'm trying to do it like so:

NSString     *myUnsignedIntString = [self someMethodReturningAString];
NSInteger    myInteger            = [myUnsignedIntString integerValue];
NSNumber     *myNSNumber          = [NSNumber numberWithInteger:myInteger];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

Will the above potentially "cut off" the end of a large unsigned int since I had to convert it to NSInteger first? Or does it look OK to use? If it'll cut off the end of it, how about the following (a bit of a kludge I think)?

NSString     *myUnsignedIntString = [self someMethodReturningAString];
long long    myLongLong           = [myUnsignedIntString longLongValue];
NSNumber     *myNSNumber          = [NSNumber numberWithLongLong:myLongLong];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

Thanks for any help you can offer! :)


回答1:


The first version truncates and the second should be fine as long as your number actually fits into an unsigned int - see e.g. "Data Type Size and Alignment".
You should however create the NSNumber using +numberWithUnsignedInt.

If you know that the encoding is suitable, you could also simply go with the C-libraries:

unsigned n;
sscanf([str UTF8String], "%u", &n);


来源:https://stackoverflow.com/questions/2824110/how-to-convert-an-nsstring-to-an-unsigned-int-in-cocoa

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