【问题标题】:Create JSON from Core Data从核心数据创建 JSON
【发布时间】:2013-07-01 08:27:57
【问题描述】:

如何从 Core Data 实体及其 1:m 子实体中创建带有 NSJSONSerializationJSON 对象?

当尝试在将提取请求转换为 JSON 之前将其输出到 NSDictionary 时,我得到一个没有任何关系的平面 NSDictionary,或者在将 propertiesToFetch 设置为关系时我的应用程序崩溃。

这是我的代码:

NSFetchRequest *request = [NSFetchRequest 
   fetchRequestWithEntityName:@"ContrSector"];
request.resultType = NSDictionaryResultType;
request.propertiesToFetch = @[@"industries"];
NSError *error;
NSArray *result = [self.managedObjectContext 
    executeFetchRequest:request error:&error];

这样做的正确方法是什么?

【问题讨论】:

    标签: ios objective-c json core-data nsdictionary


    【解决方案1】:

    propertiesToFetch 需要 NSPropertyDescription 的实例,因此请尝试将 @"industries" 替换为:

    NSDictionary *attributes = [[NSEntityDescription entityForName"@ContrSector" inManagedObjectContext:self.managedObjectContext] relationshipsByName];
    NSAttributeDescription *industriesRelationship = [attributes objectForKey:@"industries"];
    
    request.propertiesToFetch = @[industriesRelationship];
    

    编辑:我没有意识到这是一个多对多的关系,来自文档:

    属性描述可以表示属性,一对一 关系或表达。属性的名称或 关系描述必须与 获取请求的实体。

    【讨论】:

    • 它与Invalid to many relationship ((<NSRelationshipDescription: 0x10057ac90>), name industries, isOptional 1, isTransient 0, entity ContrSector, renamingIdentifier industries...一起崩溃
    • 只使用“行业”时会发生什么崩溃?
    • -[NSSQLToMany foreignEntityKey]: unrecognized selector sent to instance 0x100185460
    • 我面临与@AlexR 相同的问题。有人解决了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2012-08-22
    相关资源
    最近更新 更多