【问题标题】:NSMutableDictionary setValue:forUndefinedKeyNSMutableDictionary setValue:forUndefinedKey
【发布时间】:2014-08-17 19:01:53
【问题描述】:

我正在开发一个 iOS 应用。我有一个扩展 NSObject 的类,它定义了 1 个属性

//.h file
@property (nonatomic,retain) NSMutableDictionary *livedata; 


//.m file
if(self = [super init]){
    self.livedata = [[NSMutableDictionary alloc] init];
    [self.livedata setValue:@"myvalue" forUndefinedKey:@"myUndefinedKey"];
}

我收到此错误。 * 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类与键 myUndefinedKey 的键值编码不兼容。”

我过去曾将 NSMutableDictionary 用于 kvc、kvo。是的,我看到这个类不符合 kvc。

【问题讨论】:

  • 你想要setValue:forKey 而不是setValue:forUndefinedKey
  • 效果很好。非常感谢!

标签: ios objective-c nsmutabledictionary key-value-observing kvc


【解决方案1】:

问题是您调用的方法在调用时会引发异常。 setValue:forUndefinedKey: 仅在 setValue:forKey: 引用 this article 找不到给定键的属性时调用。相反,只需调用

[self.livedata setValue:@"myvalue" forKey:@"myKey"];

【讨论】:

    【解决方案2】:

    你想要setValue:forKey: 而不是setValue:forUndefinedKey:

    [self.livedata setValue:@"value" forKey:@"key"];
    

    系统调用setValue:forUndefinedKey,该方法可以覆盖。

    来自文档:
    setValue:forKey: 在找不到给定键的属性时调用。

    “子类可以重写此方法以其他方式处理请求。默认实现引发NSUndefinedKeyException。”

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2015-09-16
      • 2012-06-05
      • 2014-12-10
      • 2016-02-27
      • 2020-08-31
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      相关资源
      最近更新 更多