如何从 Core Data 实体及其 1:m 子实体中创建带有 NSJSONSerialization 的 JSON 对象?
当尝试在将 fetch 请求转换为 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];
这样做的正确方法是什么?
Best Answer-推荐答案 strong>
propertiesToFetch 需要 NSPropertyDescription 的实例,因此请尝试将 @"industries"替换为:
NSDictionary *attributes = [[NSEntityDescription entityForName"@ContrSector" inManagedObjectContext:self.managedObjectContext] relationshipsByName];
NSAttributeDescription *industriesRelationship = [attributes objectForKey"industries"];
request.propertiesToFetch = @[industriesRelationship];
编辑:我没有意识到这是一个多对多的关系,来自文档:
The property descriptions may represent attributes, to-one
relationships, or expressions. The name of an attribute or
relationship description must match the name of a description on the
fetch request’s entity.
关于ios - 从核心数据创建 JSON,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/17451543/
|