Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to NSUInteger

I've got a number in a NSString @"15". I want to convert this to NSUInteger, but I don't know how to do that...

like image 566
dododedodonl Avatar asked May 01 '10 11:05

dododedodonl


2 Answers

NSString *str = @"15";
// Extract an integer number, returns 0 if there's no valid number at the start of the string.
NSInteger i = [str integerValue];

If you really want an NSUInteger, just cast it, but you may want to test the value beforehand.

like image 162
squelart Avatar answered Oct 13 '22 21:10

squelart


The currently chosen answer is incorrect for NSUInteger. As Corey Floyd points out a comment on the selected answer this won't work if the value is larger than INT_MAX. A better way of doing this is to use NSNumber and then using one of the methods on NSNumber to retrieve the type you're interested in, e.g.:

NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;
like image 20
Zach Dennis Avatar answered Oct 13 '22 22:10

Zach Dennis