7

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

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Dave
  • 12,408
  • 12
  • 64
  • 67
  • To request support for reading unsigned values from NSString, please visit http://bugreport.apple.com and file a dupe of radar://2264733 against component `Foundation | X`. – Quinn Taylor Jan 23 '13 at 05:45

1 Answers1

8

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);
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236