您的位置:首页 > 移动开发

Terminating app due to uncaught execption'NSUnknownKeyException'的解决方式

2016-06-30 15:12 519 查看
Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key youHuiCardUsedM.’

* First throw call stack:

(

0 CoreFoundation 0x000000010db53d85 __exceptionPreprocess + 165

1 libobjc.A.dylib 0x000000010cd0bdeb objc_exception_throw + 48

我们在处理从服务器获取到的数据的时候,会遇到上面的问题,主要原因是因为你在字典转模型时调用了如下的方法:

setValuesForKeysWithDictionary


调用完这个方法之后,对于数据模型中缺少的、不能与任何键配对的属性的时候,系统会自动调用setValue:forUndefinedKey:这个方法,该方法默认的实现会引发一个NSUndefinedKeyExceptiony异常。

如果想要程序在运行过程中不引发任何异常信息且正常工作,可以让数据模型类重写setValue:forUndefinedKey:方法以覆盖默认实现,而且可以通过这个方法的两个参数获得无法配对键值。

有两个方法,下面详解:

- (nullable id)valueForUndefinedKey:(NSString *)key;


官方的解释是:

Given that an invocation of -valueForKey: would be unable to get a keyed value using its default access mechanism, return the keyed value using some other mechanism. The default implementation of this method raises an NSUndefinedKeyException. You can override it to handle properties that are dynamically defined at run-time.

鉴于-valueForKey的调用:将无法得到一个键值使用其默认访问机制,返回键的值使用一些其他的机制。该方法的默认实现提出了一个NSUndefinedKeyException。你可以覆盖它来处理在运行时动态地定义属性。

- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;


官方解释如下:

Given that an invocation of -setValue:forKey: would be unable to set the keyed value using its default mechanism, set the keyed value using some other mechanism. The default implementation of this method raises an NSUndefinedKeyException. You can override it to handle properties that are dynamically defined at run-time.

鉴于setvalue的调用:forKey:将无法使用其默认设置键值机制,设置键值使用一些其他的机制。该方法的默认实现提出了一个NSUndefinedKeyException。你可以覆盖它来处理在运行时动态地定义属性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios Key