2013-07-22 34 views
2

我的問題是「R real:」的結果是完美的,但是當我將例如'cloth.R'轉換爲int時,結果爲0.我該如何解決這個問題。 謝謝。爲什麼我的NSString int在Objective C中是錯誤的?

Cloth *cloth = [app.clothArray objectAtIndex:0]; 
NSLog(@"R real:%@",cloth.R); 
NSLog(@"G real:%@",cloth.G); 
NSLog(@"B real:%@",cloth.B); 

NSString *aNumberString = cloth.R; 
int i = [aNumberString intValue]; 
NSLog(@"NSString:%@",aNumberString); 
NSLog(@"Int:%i",i); 

結果:

2013-07-22 18:57:45.965 App_ermenegild[26030:c07] R real: 
232 
2013-07-22 18:57:45.965 App_ermenegild[26030:c07] G real: 
0 
2013-07-22 18:57:45.965 App_ermenegild[26030:c07] B real: 
121 
2013-07-22 18:57:45.966 App_ermenegild[26030:c07] NSString: 
232 
2013-07-22 18:57:45.966 App_ermenegild[26030:c07] Int:0 

編輯
這裏是Cloth

@interface Cloth : NSObject 
@property(nonatomic,retain) NSString *nom; 
@property(nonatomic,retain) NSString *R; 
@property(nonatomic,retain) NSString *G; 
@property(nonatomic,retain) NSString *B; 
@property(nonatomic,retain) NSString *col; 
@property (nonatomic,readwrite) NSInteger *clothID; 
@end 

這裏XML文件模式:

<cloth id="1"> 
<nom>Heliconia</nom> 
<R>232</R> 
<G>0</G> 
<B>121</B> 
<col>#E80079</col> 
</cloth> 
+1

'cloth.R'絕對是'NSString'對象嗎? – trojanfoe

+1

...如果是,並且用於保存R,G,B值,那麼*爲什麼*它是一個'NSString'對象而不是'int'? – trojanfoe

+0

爲什麼你將R,G,B作爲NSString存儲在布料中? 使用CGFloat。 或更好具有UIColor屬性。 –

回答

2

唯一的情況是,當你在開始時有不可見的字符時,新行字符

例如

NSString *cloth = @"\n232"; 
int i = [cloth intValue]; 
NSLog(@"NSString:%@",cloth); 
NSLog(@"Int:%i",i); 

和日誌

2013-07-22 22:14:57.560 DeviceTest[801:c07] NSString: 
232 
2013-07-22 22:14:57.561 DeviceTest[801:c07] Int:0 

這就是爲什麼我問你確切的日誌輸出。

+0

是的,這正是我所遇到的問題。但是當我閱讀並保存它時,空間就會出現。我上傳它。 – user2607430

+0

這就是爲什麼我想看看RGB值設置在哪裏。 –

+0

@ user2607430你在哪裏上傳..鏈接請 –

0

%i對於 NSString不是 format specifier。編譯器和/或NSString應該警告你。

恩,該死。每天學些新東西!仍然使用%d而不是%i

嘗試%d

NSLog(@"Int:%d",i); 

如果不工作,那麼請檢查你有你的字符串不可見字符goobers。我建議測試一下這個長度,看看它是否合理。

找到缺失的字符可能非常棘手,因爲許多Unicode字符序列在很多情況下都不可見。一個十六進制編輯器可以告訴你發生了什麼,但這是一個簡單的,駭人聽聞的測試,對於簡短的字符串很適合。

int main(int argc, char *argv[]) { 
    @autoreleasepool { 
     NSString *good = @"10"; 
     NSString *bad = @"1\u20630"; 

     NSLog(@"%@ %@", good, bad); 

     NSLog(@"%d %d", [good intValue], [bad intValue]); 

     NSData *dGood = [good dataUsingEncoding:NSUTF8StringEncoding]; 
     NSData *dBad = [bad dataUsingEncoding:NSUTF8StringEncoding]; 

     NSLog(@"%@ %@", dGood, dBad); 
    } 
} 

輸出:

2013-07-22 09:58:44.654 Untitled[1105:507] 10 1⁣0 
2013-07-22 09:58:44.656 Untitled[1105:507] 10 1 
2013-07-22 09:58:44.656 Untitled[1105:507] <3130> <31e281a3 30> 

0x31對於1字符的ASCII。 0x300。顯然,壞字符串在1和0之間有一堆gobbledygook。將你的字符串轉換爲NSData並記錄下來。


通常,應該使用NSIntegerNSUInteger來存儲由該系統提供的數字值使用位寬特定類型。這會導致代碼變得更脆弱,特別是如果在編譯器中打開「不安全的轉換」警告。另外:如果確實是一種顏色,請將其存儲爲UIColorNSColor的實例。至少拼出組件的名稱,因爲它會使代碼閱讀更流利。

+0

他使用%i作爲整數 –

+0

他們使用'%i'記錄的唯一東西是變量'i',它是'int'。 – Jim

+0

@InderKumarRathore'%i'不代表「整數」;這並不意味着什麼。 '%d'表示*帶符號的32位整數*。 – bbum

相關問題