PeterK
PeterK

Reputation: 4301

Why do i get an error comparing NSString's? (-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance)

I have a NSMutableArray (_theListOfAllQuestions) that I am populating with numbers from a file. Then I compared the objects in that array with qNr (NSString) and I got error. I even casted the array to another NSString, _checkQuestions, just to be sure I am comparing NSStrings. I tested using item to compare also.

-(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++;
 }

When running this code i get the following NSLog:

read_A_Question: 421
item: 1193
_checkQuestions: 1193

...and error:

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

I do believe that I still comparing NSString with a number of some sort but to me it looks like I am comparing NSString vs. NSString?

I could really need some help here to 1) understand the problem, 2)solve the problem?

Upvotes: 9

Views: 8765

Answers (2)

P.J
P.J

Reputation: 6587

Replace this line

if ([_checkQuestions isEqualToString:qNr])

with

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

Hope it helps you..

Upvotes: 15

iDev
iDev

Reputation: 23278

Your _theListOfAllQuestions array has NSNumber objects and not NSString objects. So you cant use isEqualToString directly.

Try this,

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++;
 }

Upvotes: 2

Related Questions