设置具有多个实体的FetchedResultsController

时间:2014-06-11 11:55:20

标签: cocoa-touch uitableview core-data nsfetchedresultscontroller

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

我想在UITableView中做的一切非常简单 - 我希望UITableViewSections成为相应的EventCluster个对象,并且该部分的每一行都是Event将按eventID值排序的对象。

现在我所做的就是:

- (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结构?

1 个答案:

答案 0 :(得分:0)

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

parentCluster:@"parentCluster.customMethod"

和这(我写的是这个,但你明白了)

@implementation EventCluster (CategoryName)

- (NSString *)customMethod
{
    return self.objectID.URIRepresentation.absoluteString;
}

@end