2012-10-24 103 views
18

我有這一點的目標C代碼,我在哪裏鑄造NSStringint目標C - 類型轉換從的NSString INT

NSString *[email protected]"123abc"; 
NSInteger b=(int) a; 
NSLog(@"b: %d",b); 

而且NSLog產生這樣的輸出:

b: 18396 

任何人都可以向我解釋爲什麼會發生這種情況嗎?

我在印象類型下將字符串轉換爲整數將從字符串中獲得數值。

+0

獲取數值從字符串:http://stackoverflow.com/questions/4663438/objective-c-find-numbers-in-string – janusbalatbat

回答

31

您已經得到了指向NSString對象的指針的整數值。解析字符串爲整數,你應該做的:

NSString *a = @"123abc"; 
NSInteger b = [a integerValue]; 
5

當您將一個對象轉換爲整數時,您將獲得指向內存地址的指針。您可以撥打[a integerValue]獲取字符串的整數值。

此外,當鑄造它最好使用NSInteger instate of int。因爲當使用64位操作系統時,NSInteger將是64位。

10

要得到的數值使用:

int val = [stringObj intValue]; 

NSInteger

NSInteger val = [stringObj integerValue]; 
0

或用Objective-C的文字語法:

@([a intValue]); 
+0

你得到NSNumber *在這裏,而不是NSInteger – Cfr