marciokoko
marciokoko

Reputation: 4986

NSNumber being recognized as NSString in if-else

I have this bit of code thats got me crazy. Its a cellForRowAtIndexPath displaying 4 properties, of which 2 are NSStrings and 2 are NSNumber:

//THIS LOGS THE OBJECT BEFORE PROCESSING
NSLog(@"NO DATE EDITING");
NSLog(@"eFK: %@, eFN: %@",editedFieldKey, editedFieldName);
NSLog(@"editedObject vWA is:%@", editedObject);
NSLog(@"Is of type NSString?: %@", ([editedFieldKey isKindOfClass:[NSString class]])? @"Yes" : @"No");
//THIS TESTS TO SEE IF ITS A NSSTRING
if ([editedFieldName isKindOfClass:[NSSTRING class]]) {
    NSLog(@"its nsstring");
    textField.text = [editedObject valueForKey:editedFieldKey];
    NSLog(@"its NOT nsstring");
    }
} else {
//ELSE ITS A NUMBER SO GET ITS STRING VALUE BEFORE ASSIGNING
    textField.text = [[editedObject valueForKey:editedFieldKey] stringValue];
    // And we set the switch to ON if YES, OFF if NO...
    if ([editedObject valueForKey:editedFieldKey]) {
        NSLog(@"itemreceived equal to 1");
        itemReceived.on = YES;
    } else {
        NSLog(@"itemreceived equal to 0");
        itemReceived.on = NO;
}
[textField becomeFirstResponder];

I have 4 fields, 2 NSStrings and 2 NSNumbers. When I tap on the string fields, I get its a string and it works fine. But if i click on one of the number fields, I get its a string and NSCFNumber isNaturallyRTL...unrecognized selector sent to instance at the:

textField.text = [editedObject valueForKey:editedFieldKey];

Why is my test failing? Why even when I select a number, which is not a string, the app goes thru the first if condition as if it were a string?

Upvotes: 0

Views: 343

Answers (2)

Dirk
Dirk

Reputation: 31053

Hm. This is just a guess... But first:

NSLog(@"Is of type NSString?: %@", ([editedFieldKey isKindOfClass:[NSString class]])? @"Yes" : @"No");

Here, you look at editedFieldKey.

if ([editedFieldName isKindOfClass:[NSSTRING class]]) {

Here you are looking at editedFieldName. In neither case, I looks like as if your were testing the actual value.

Upvotes: 0

Craig Otis
Craig Otis

Reputation: 32054

If I had to guess, I'd say you're testing the type of the wrong variable. Instead of:

...
if ([editedFieldName isKindOfClass:[NSSTRING class]]) {
...

Just based on your variable names (as your question is a bit lacking in details), it seems you instead want:

...
if ([[editedObject valueForKey:editedFieldKey] isKindOfClass:[NSSTRING class]]) {
...

I left your typos in the snippets - this can't be compiling though. Aren't you actually using [NSString class] instead of [NSSTRING class]? Note the capitalization difference.

Upvotes: 3

Related Questions