objective-c - iOS崩溃: “this class is not key value coding-compliant for the key url”

标签 objective-c dictionary crash

我在crashlytics上遇到以下崩溃。

Fatal Exception: NSUnknownKeyException [<__NSCFString 0x1742aeb80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.



这是某些用户崩溃的地方。
 id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];

我不确定防止此崩溃的最佳方法是什么。我相信这是因为json[@"data"]在某些情况下是NSString。所以我相信我应该检查这是否是NSDictionary这样的。
if ([json[@"data"] isKindOfClass:[NSDictionary class]]) {
     id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
    }

任何提示或建议,不胜感激。

这是我从这里得到答案后的最终结果。这样看起来还好吗?起初,我并没有包含所有代码,以使事情变得简单。
        if ([json isKindOfClass:[NSDictionary class]]) {
            id url = nil;
            id type = nil;

            NSDictionary *data = json[@"data"];

            if ([data isKindOfClass:[NSDictionary class]]) {
                type = data[@"type"];
                NSDictionary *value = data[@"value"];

                if ([value isKindOfClass:[NSArray class]]) {
                    url = [value valueForKey:@"url"];
                }

                if ([type isKindOfClass:[NSString class]] && [url isKindOfClass:[NSArray class]] && [url count] != 0) {
                   // do stuff
              }
            }
         }

最佳答案

您应该一一检查NSDictionary以防止崩溃。在下面尝试我的代码

NSDictionary *dictionary = json[@"data"];
NSString *output = @"";
if ([dictionary isKindOfClass:[NSDictionary class]]) {
  dictionary = dictionary[@"value"];
  if ([dictionary isKindOfClass:[NSDictionary class]]) {
    output = dictionary[@"url"];
  }
}
NSLog(@"%@", output);

您由于对valueForKey值调用NSString方法而崩溃。如果有人说崩溃的原因是字典没有此键时调用valueForKey,那是错误的。有关更多信息Sending a message to nil in Objective-C

如果NO为nil,则[dictionary isKindOfClass:[NSDictionary类]]始终返回dictionary,因此无需检查dictionary中的if statement。这是不必要的。

关于objective-c - iOS崩溃: “this class is not key value coding-compliant for the key url”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290511/

相关文章:

objective-c - 仅 "extern const"与 "extern"

iphone - 禁止在受监管设备上进行操作

iphone - 使用 NSString 作为 NSString 数组?

ios - SKPhysicsContact 崩溃的扩展

ios - 为什么 NSManagedObject 实例不持有对其 NSManagedObjectContext 的强引用?

Python:从字典中获取具有最小值但有多个最小值的键

Python:检查是否有任何列表元素是字典中的键

crash - Tomcat在以下3条消息后被停止:收到无效的消息,签名为18245

iphone - 内存警告和崩溃问题

c# - 保持我的列表/词典在全局范围内可访问