Search code examples
iosobjective-cnsarraynsdictionary

iOS: Looking for NSDictionary value I get error: [__NSCFNumber isEqualToString:]: unrecognized selector sent to instanc


I'm getting Json response with subArrays of dictionaries and I'm looking for particular value inside of one the subArrays. This is the subArray I care about:

<__NSArrayM 0x600000047680>(
{
    value = "VeryImportanValue";
},
{
    value = "someValue";
},
{
    value = 0912131235235234;
}
)

I'm looking for the dictionary with the value of "VeryImportanValue". But as you can see you of the values are numeric and I check:

if ([[dict objectForKey:@"value"]isEqualToString:@"VeryImportanValue"])

I get this error:

 -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance

But switch the if statement to fix the error above:

 if ([[[dict objectForKey:@"value"] stringValue] isEqualToString:@"VeryImportanValue"])

I get this error:

-[__NSCFString stringValue]: unrecognized selector sent to instance 

How can I check the value of the dictionary without getting any of this errors regarless if is string or numeric value?

I'll really appreciate your help.


Solution

  • You could create a method that turns the unknown object into a string:

    - (NSString *)stringForStringOrNumber:(id)object
    {
        NSString *result = nil;
        if ([object isKindOfClass:[NSString class]]) {
            result = object;
        } else if ([object isKindOfClass:[NSNumber class]]) {
            result = [object stringValue];
        } else {
            result = @"I can't guess";
        }
        return result;
    }