2013-01-21 39 views
9

我有一個NSMutableArray (_theListOfAllQuestions),我用一個文件中的數字填充。然後我將該陣列中的對象與qNr (NSString)進行比較,發現錯誤。我甚至將陣列鑄造成另一個NSString_checkQuestions,只是爲了確保我比較NSStrings。我測試使用項目也比較。爲什麼我比較NSString的時候出錯? ( - [__ NSCFNumber isEqualToString:]:無法識別的選擇器發送到實例

-(void)read_A_Question:(NSString *)qNr { 
NSLog(@"read_A_Question: %@", qNr); 
int counter = 0; 
for (NSString *item in _theListOfAllQuestions) { 
    NSLog(@"item: %@", item); 
    _checkQuestions = _theListOfAllQuestions[counter]; //_checkQuestion = NSString 
    NSLog(@"_checkQuestions: %@", _checkQuestions); 
    if ([_checkQuestions isEqualToString:qNr]) { 
     NSLog(@">>HIT<<"); 
     exit(0); //Just for the testing 
    } 
    counter++; 
} 

運行此代碼我得到以下NSLog

read_A_Question: 421 
item: 1193 
_checkQuestions: 1193 

...和錯誤:

-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9246d80 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9246d80'

我相信我還是有一些比較一些NSString排序,但對我來說,它看起來像我比較NSStringNSString

我真的可以在這裏得到一些幫助1)理解問題,2)解決問題?

+0

那好吧'_checkQuestions',至少在一種情況是'NSNumber',而不是'NSString' 。 '_theListOfAllQuestions'究竟是什麼?那是如何填充的? –

回答

15

替換該行

if ([_checkQuestions isEqualToString:qNr]) 

if ([[NSString stringWithFormat:@"%@",_checkQuestions] isEqualToString:[NSString stringWithFormat:@"%@",qNr]]) 

希望它可以幫助你..

+2

由於'NSNumber'已經有一個'-stringValue'屬性,所以'stringWithFormat'不需要'stringWithFormat',它以字符串的形式返回數字。 –

+0

@yulz我不知道_checkQuestions的數據類型,並且在使用stringWithFormat時沒有任何傷害。 –

+0

@Praatek,這使得它感謝。 – PeterK

2

您的_theListOfAllQuestions數組有NSNumber對象而不是NSString對象。所以你不能直接使用isEqualToString

試試這個,

for (NSString *item in _theListOfAllQuestions) { 
    NSLog(@"item: %@", item); 
    _checkQuestions = _theListOfAllQuestions[counter]; //_checkQuestion = NSString 
    NSLog(@"_checkQuestions: %@", _checkQuestions); 
    if ([[_checkQuestions stringValue] isEqualToString:qNr]) { 
     NSLog(@">>HIT<<"); 
     exit(0); //Just for the testing 
    } 
    counter++; 
} 
+0

ABC,早先試過這個,並且得到「沒有可見的@interface for'NSString'聲明選擇器'stringValue'」 – PeterK

+0

這是因爲你應該聲明'_checkQuestions'爲NSNumber而不是NSSString。你的數組有NSNumbers而不是字符串。在這種情況下,不推薦使用'[NSString stringWithFormat:@「%@」,_ checkQuestions]'。這會在以後得到意想不到的結果 – iDev

+1

設置_checkQuestions爲'NSNumber'。你可以在你的if語句中輸入'[(NSNumber *)_ checkQuestions stringValue]',或者將你已經聲明瞭_checkQuestions的類型改爲NSNumber –

相關問題