开发者

NSString to NSUInteger

开发者 https://www.devze.com 2022-12-28 15:33 出处:网络
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...NSString *str = @\"15\";

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...


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.


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;


All these answers are wrong on a 64-bit system.

NSScanner *scanner = [NSScanner scannerWithString:@"15"];
unsigned long long ull;
if (![scanner scanUnsignedLongLong:&ull]) {
  ull = 0;  // Or handle failure some other way
}
return (NSUInteger)ull;  // This happens to work because NSUInteger is the same as unsigned long long at the moment.

Test with 9223372036854775808, which won't fit in a signed long long.


you can try with [string longLongValue] or [string intValue]..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号