CoreData NSFetchedResultsController排序

Jos*_*ane 2 core-data objective-c nsfetchedresultscontroller ios

排序我的问题很小NSFetchedResultsController.

NSManagedObject有两个属性.datestartTime.

date我所有的对象是时间00:00:00,当使用这种方式datesectionNameKeyPath它抓住所有具有相同日期的对象(按天)为一个部分.如果日期的时间不同,它会将每个对象放入不同的部分.

这很好用,但是在每个组中我想要按对象排序startTime.因此,它们分别从最早date到每个部分的最新列表.

使用时,我的问题是,date作为sectionNameKeyPathstartTime作为NSSortDescriptor`它不喜欢它,古怪播放.比如有时只是在看似不规则的方式中显示某些数据.

我认为这归结为必须具有排序描述符和sectionNameKeyPath相同.我是否正确地思考这个?如果没有,我应该如何设置我NSFetchedResultsController以所提到的方式列出我的数据?

谢谢.

编辑:这是代码...当使用startTime作为我的第二个排序描述符时,值得注意的是,它会导致重复项在我的tableview中显示为nil对象.

NSFetchedResultsController:

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:YES];
    NSArray *sortDescriptors = @[sortDescriptor1, sortDescriptor2];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"date" cacheName:@"Master"];
Run Code Online (Sandbox Code Playgroud)

cellForRowAtIndexPath 只是一个片段,显示我如何指定每个托管对象:

id <NSFetchedResultsSectionInfo> sectionInfo = [self.flightFetchedResultsController.sections objectAtIndex:indexPath.section];
    NSArray *sectionFlights = [sectionInfo objects];
    Flight *flight = [sectionFlights objectAtIndex:indexPath.row];

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.flightFetchedResultsController.sections.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.flightFetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}
Run Code Online (Sandbox Code Playgroud)

Fog*_*ter 5

您的部分密钥名称路径需要与第一个排序描述符匹配.

所以你可以......

// sectionKeyNamePath = @"date".

NSSortDescriptor *dateSD = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
NSSortDescriptor *startTimeSD = [NSSortDescriptor sortDescriptorWithKey:@"startTime" ascending:YES];

frc.request.sortDescriptors = @[dateSD, startTimeSD];
Run Code Online (Sandbox Code Playgroud)

如果你这样做,那么它将按日期排序(和部分),然后按startTime对每个部分进行排序.

从你的代码

您正在获取错误的获取对象.

要获得一个对象,你需要使用...

Flight *flight = [self.frc objectAtIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

获取的结果控制器知道其节和行.你不需要将它拆开.