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

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

我得到 Json 字典子数组的响应,我正在寻找一个子数组中的特定值。这是我关心的子数组:

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

我正在查找值为 "VeryImportanValue" 的字典。但是正如您所看到的,这些值是数字的,我检查了:

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

我收到这个错误:

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

但是切换if语句来修复上面的错误:

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

我收到这个错误:

-[__NSCFString stringValue]: unrecognized selector sent to instance 

无论是字符串还是数字值,如何检查字典的值而不出现任何错误?

非常感谢你的帮助。

您可以创建一个将未知对象转换为字符串的方法:

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

在执行 isEqualToString 之前,您应该首先检查字典的值类型。

  if(dict[@"value"]isKindOfClass==[NSString class]) //value is string