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

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。你可以覆盖它来处理在运行时动态地定义属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值