2013-02-26 152 views
1

我有,我要轉換爲一個NSNumber一個NSString一個簡單的值。我在我的代碼中一直這樣做,出於某種原因,這次它不起作用。你看到有什麼問題嗎?崩盤的NSString轉換爲NSNumber的

NSNumberFormatter * num_formatter = [[NSNumberFormatter alloc] init]; 
[num_formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
NSNumber *score; 
NSString *mystr = [[player ScoresArray] objectAtIndex:currentKeeper - 1]; 


NSLog(@"here is my string: -%@-", mystr); 
score = [num_formatter numberFromString:mystr]; // crash occurs on this line. see error below... 
NSLog(@"now it is: %d", [score intValue]);  // it never gets to this line... 

這裏是從上面的代碼的輸出:

這裏是我的字符串:-3-

這裏是我的錯誤:

2013-02-26 17:21:48.912 Golf Whiz[50407:c07] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xcb5fa90 
2013-02-26 17:21:48.912 Golf Whiz[50407:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xcb5fa90' 
*** First throw call stack: 
+3

'mystr'是'NSNumber',而不是一個'NSString'。顯示你如何定義和賦值給'mystr'。 – rmaddy 2013-02-26 22:45:21

+0

另外...使用%i而不是%d在線時,它永遠不會得到它,當你得到它的工作...%d是雙打...你拿了「intValue」(INTEGER),所以你想%i整數。 – 2013-02-26 22:47:48

+5

@AlbertRenshaw不,'%i'和'%d'是同樣的東西 - 用於'int'。 '%f'是'double'。 – rmaddy 2013-02-26 22:50:05

回答

1

確保您添加到ScoresArray的對象實際上是字符串,而不是NSNumbers。

+1

感謝您的支持:)這屬於評論部分,以備將來參考,但保持幫助別人的好工作! – 2013-02-26 22:57:31

0

感謝,全部爲疑似,事實證明,我確實有在scoresArray NSNumber的對象畢竟。在這段代碼中,我已經從字符串到數字之間來回移動,以至於我的腦袋即將爆炸。比較遺憾的是跛腳的問題 - 我想,如果我現在可以下投我自己的問題...笑