我在NSString @"15"里有个号码。我想把它转换成NSUInteger,但我不知道该怎么做...
发布于 2010-05-01 19:30:38
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];如果你真的想要一个NSUInteger,就强制转换它,但是你可能想要预先测试它的值。
发布于 2014-04-02 04:16:27
对于NSUInteger,当前选择的答案不正确。正如Corey Floyd指出的对所选答案的评论,如果值大于INT_MAX,这将不起作用。一种更好的方法是使用NSNumber,然后使用NSNumber上的方法之一来检索您感兴趣的类型,例如:
NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;发布于 2016-01-07 03:08:07
所有这些答案在64位系统上都是错误的。
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.使用9223372036854775808进行测试,它不适合带签名的long long。
https://stackoverflow.com/questions/2749720
复制相似问题