【问题标题】:Core Data Transformable Attribute核心数据可转换属性
【发布时间】:2012-09-05 21:11:09
【问题描述】:

我正在尝试访问可转换核心数据对象的属性,如下所示:

MainObject *localObject = [self.myArray objectAtIndex:indexPath.row];
TransformableObject *actualObject = localObject.transformableObject;

这很好用。我NSLogactualObject 并得到正确的键/值对:

actualObject:{

    property = "Foo";
    property2 = "Apple";
}

但是,当我尝试:

NSLog (@"property:%@",actualObject.property)我得到-[__NSCFDictionary property]: unrecognized selector sent to instance

我做错了什么?在我的核心数据类中,我有:

@interface MainObject : NSManagedObject

@property (nonatomic, retain) TransformableObjectClass *transformableObject;

编辑: 这是我在 Core Data 中设置对象的方式

        MainObject *event = (MainObject *)[NSEntityDescription insertNewObjectForEntityForName:@"MainObject" inManagedObjectContext:[AppDelegateMy managedObjectContext]];
        [event setValuesForKeysWithDictionary:[myArrray objectAtIndex:i]];

【问题讨论】:

  • 您最初是如何设置localObject.transformableObject 的值的?您的模型中的属性是如何配置的? actualObject 显然是 NSDictionary,但你没有给我们足够的信息来推断原因。
  • TransformableObjectClass 是另一个核心数据 NSManagedObject 类。
  • 可能是这样,但错误表明实际分配给该属性的是NSDictionary 的实例。那么,它是如何到达那里的呢?
  • 刚刚添加了一个编辑,我通过 for 循环对 JSON 响应中的每个对象进行了编辑

标签: iphone ios core-data nsdictionary nsmanagedobject


【解决方案1】:

-setValuesForKeysWithDictionary: 和 Core Data 都不够神奇,无需您付出更多努力即可完成这项工作。现在,您只需将 JSON 响应中的字典分配给新托管对象的 transformableObject 属性。如果您尝试保存上下文,我的猜测是它可能会失败。如果您希望这些字典变成实际的 TransformableObjectClass 实例,您需要自己做。

如果您的应用中有很多此类内容,您可能需要查看 RestKit,或其他开源 JSON 到对象映射库之一,例如 ClassMapper

【讨论】:

  • 它保存得很好,如果 -setValuesForKeysWithDictionary 不起作用,为什么我可以访问上面的 actualObject 作为 NSManagedObject 的属性?
  • 一切正常。它只是没有按照你的想法做。在 Objective-C 中,指针类型更具描述性而非禁止性。如果您将字典放入该属性而不是您声明的类,则运行时不会抱怨。但是,如果您尝试向该字典发送它不支持的消息,它就会崩溃。就像你看到的那样。
  • 能否发一张模型配置的截图?具体是相关属性的属性?
猜你喜欢
  • 2018-11-20
  • 2011-08-31
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 2018-07-30
相关资源
最近更新 更多