【问题标题】:Fetch Relationship Objects获取关系对象
【发布时间】:2011-10-16 05:41:06
【问题描述】:

CoreData 初学者

CoreData 有一个简单的问题。我的模型有两个实体,现在称为 A 和 B。实体 A 具有 B 实体的多对多关系,与实体 A 具有反向关系。

我正在使用以下代码检索实体 A:

NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"A"
                                          inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                           ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:descriptor]];

NSError *error = nil;
NSArray *items = [context executeFetchRequest:request error:&error];

if (error) /* ... */;

for (id item in items)
{
    /* ... */
}

[request release];
[descriptor release];

现在我想在该循环中检索 A 的关系指向的所有对象 B 的数组。我该如何实现呢?我应该创建另一个获取请求还是有更实用的方法?

我搜索过 StackOverflow 并发现了类似的问题,但有时过于模糊。

【问题讨论】:

    标签: objective-c cocoa macos core-data osx-lion


    【解决方案1】:

    NSFetchRequest 上有一个名为 -setRelationshipKeyPathsForPrefetching: 的实例方法。

    此方法采用一个键名数组,这些键名将用于预取在与这些键路径的关系中定义的任何对象。考虑使用新代码更新的示例:

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    NSString *relationshipKeyPath = @"bObjects"; // Set this to the name of the relationship on "A" that points to the "B" objects;
    NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
    [request setRelationshipKeyPathsForPrefetching:keyPaths];
    

    现在,一旦您完成了获取请求,所有这些关系对象都应该会出错并准备就绪。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      相关资源
      最近更新 更多