2011-07-19 48 views
1

由於某些原因,當我將此NSString轉換爲整數時,我得到一個完全隨機(但一致)的數字。問題將NSString轉換爲Int

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // do something with the data 
    // receivedData is declared as a method instance elsewhere 
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); 

    // release the connection, and the data object 
    [connection release]; 

    debtString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 

    NSLog(@"String form: %@", debtString); 
    [receivedData release]; 

    int debtInt = [debtString intValue]; 
    NSLog(@"Integer form: %i", debtInt); 

} 

,這是我的控制檯輸出:

2011-07-19 11:43:18.319 National Debt[50675:207] Succeeded! Received 14 bytes of data 
2011-07-19 11:43:18.320 National Debt[50675:207] String form: 14342943000000 
2011-07-19 11:43:18.320 National Debt[50675:207] Integer form: 2147483647 

如果我穿上NSLog(@"Integer form: %i", debtInt);行設置一個斷點,然後將鼠標懸停在上面的線debtString值,存在一個無效的總結。我能想到的唯一原因就是我在轉換之前釋放了debtString,但這顯然不是真的。

+5

是否有可能我們的國債已經超過了無符號整數的存儲容量!?那麼我會被詛咒。 – Perception

+0

http://stackoverflow.com/questions/2107544/types-in-objective-c-on-iphone – albertamg

回答

4

字符串的int值高於int的最大值。因此它顯示int的最大值是2.147.483.647

+0

我該如何解決這個問題? –

+1

嘗試一個「漫長的」。 NSString有[debtString longLongValue] – joern

+0

'int debtInt = [debtString longLongValue]; NSLog(@「Integer form:%lli」,debtInt);'returns'2011-07-19 12:31:52.396 National Debt [51367:207]字符串形式:14342943000000 2011-07-19 12:31:52.397 National Debt [51367:207]整數形式:432424662392489408' –