How to convert an NSString to an unsigned int in Cocoa?
- by Dave Gallagher
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! :)