2010-05-01 67 views
12

我在NSString @"15"中有一個數字。我想將其轉換爲NSUInteger,但我不知道該怎麼做......NSString到NSUInteger

+1

要請求支持從NSString中讀取未簽名的值,請訪問http://bugreport.apple.com並提交一份有關雷達:// 2264733對'component | X'。 – 2013-01-23 21:46:42

回答

25
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,只投它,但您可能需要事先測試該值。

+1

我認爲應該閱讀'[str integerValue];' – dreamlax 2010-05-02 05:26:16

+0

D'oh!修正了,謝謝dreamlax。 – squelart 2010-05-07 10:24:37

+2

有點不完整。如果該值大於INT_MAX,則這不起作用。如果這是很有可能的,如果你使用它的字節長度的東西。 – 2010-10-15 07:45:49

0

你可以用[string longLongValue][string intValue]嘗試..

17

當前選擇的答案對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; 
+0

這也沒用! – hasan83 2015-04-30 15:36:20

+0

請在評論hasan83中更具描述性。你究竟做了什麼沒有工作? – 2015-05-05 05:08:56

+0

一個適合nsuinteger但不在nsinteger中的值確實得到了轉換。 – hasan83 2015-05-05 09:13:08

1

所有這些答案都是錯的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