使用多个实体设置 FetchedResultsController

Posted

技术标签:

【中文标题】使用多个实体设置 FetchedResultsController【英文标题】:Setting up FetchedResultsController with multiple entities 【发布时间】:2014-06-11 11:55:19 【问题描述】:

我在Core Data 中有几个实体。一种称为EventCluster,用于保存和构造Event 对象。

我想要在我的UITableView 中做的所有事情都非常简单——我希望UITableViewSections 成为相应的EventCluster 对象,并且该部分的每一行都是一个Event 对象,它将按@987654328 排序@值。

现在我所做的就是:

- (NSFetchedResultsController *)fetchedResultsController 

    if (_fetchedResultsController != nil) 
        return _fetchedResultsController;
    

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"eventID" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    [fetchRequest setFetchBatchSize:20];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:_managedObjectContext
                                          sectionNameKeyPath:nil
                                                   cacheName:@"Root"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

有没有一种方便的方法可以在这里设置NSFetchedResultsController 以包含EventCluster 结构?

【问题讨论】:

尝试将 sectionNameKeyPath 设置为 @"EventCluster" @Koen,不,那行不通。与预期一样崩溃:the entity Event is not key value coding-compliant for the key "EventCluster" 他们在你的模型中没有关系? 确实如此,EventCluster 确实是 EventparentCluster 属性。问题是我还必须对 EventCluster 对象进行排序,然后对其中的 Event 对象进行排序。 然后将sectionNameKeyPath设置为@"parentCluster"。 【参考方案1】:

您需要查询事件并使用 sectionNameKeyPath: 指向 EventCluster 上的自定义方法,该方法为每个 EventCluster 返回一个唯一的 NSString:

parentCluster:@"parentCluster.customMethod"

还有这个(我是用心写的,但你明白了)

@implementation EventCluster (CategoryName)

- (NSString *)customMethod

    return self.objectID.URIRepresentation.absoluteString;


@end

【讨论】:

以上是关于使用多个实体设置 FetchedResultsController的主要内容,如果未能解决你的问题,请参考以下文章

NestJS + MySQL:如何在不设置实体的情况下连接多个数据库

如何设置具有多个实体绑定的 ElasticSearch 索引结构

使用多个实体进行 CoreData 编程

一对多删除对象不删除多个实体上的对象

使用跨越多个实体的核心数据绑定在 Cocoa 中实现父->子向下钻取

实体框架和多个模式