获取关系对象 [英] Fetch Relationship Objects

查看:131
本文介绍了获取关系对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CoreData初学者

CoreData beginner

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

I have a simple problem with CoreData. My model has two entities, now called A and B. Entity A has a to many relationship of B entities, which has a inverse relationship to entity A.

使用此代码检索实体A:

I'm retrieving entities A with this code:

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];

现在我想在这个循环中检索所有指向的对象B的数组我如何实现这一点?

Now I'd like to retrieve, inside that loop, an array of all the objects B pointed by the relationship of A. How can I achieve this? Should I create another fetch request or there is a more practical way?

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

I've searched StackOverflow and found similar questions, but too vague sometimes.

推荐答案

NSFetchRequest 上有一个实例方法 -setRelationshipKeyPathsForPrefetching: / code>。

NSFetchRequest has an instance method on it called -setRelationshipKeyPathsForPrefetching:.

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

This method takes an array of key names that will be used to prefetch any objects defined in relationships with those key paths. Consider your example, updated with the new code:

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];

现在,一旦您完成了获取请求,所有这些关系对象都应该被破坏并准备好。

Now once you complete your fetch request, all of those relationship objects should be faulted in and ready to go.

这篇关于获取关系对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆