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

Posted by Dave Gallagher on Stack Overflow See other posts from Stack Overflow or by Dave Gallagher
Published on 2010-05-13T02:26:08Z Indexed on 2010/05/13 2:34 UTC
Read the original article Hit count: 335

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! :)

© Stack Overflow or respective owner

Related posts about cocoa

Related posts about nsstring