14

我在 NSString 中有一个数字@"15"。我想将其转换为 NSUInteger,但我不知道该怎么做...

4

4 回答 4

27
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,只需转换它,但您可能需要事先测试该值。

于 2010-05-01T11:30:38.217 回答
19

当前选择的答案对于 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;
于 2014-04-01T20:16:26.893 回答
7

所有这些答案在 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.

于 2016-01-06T19:08:07.127 回答
0

你可以试试[string longLongValue]or [string intValue]..

于 2010-05-01T11:30:11.993 回答