2

所以我有这个自定义生成的数组来定义我的部分UITableView,但是你可以看到所有的项目都是通过核心数据获取并单独排序的。

这是我的自定义代码:

-(NSArray *)tasks {
    NSManagedObjectContext *managedObjectContext = [self.fetchedResultsController managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    // retrive the objects with a given value for a certain property
    [request setPredicate:nil];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"scheduledDate" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request 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:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;

    NSError *error = nil;
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&error];

    if ((result != nil) && ([result count]) && (error == nil)){
         return [NSMutableArray arrayWithArray:result];
    }
    return [NSMutableArray array];
}

-(NSMutableArray *)sectionsArray {
    // Fetch the scheduledDate check if it is in any of the term arrays and dump it in that section.
    NSArray *tasks = [self tasks]; 
    if (tasks) {
        NSArray *scheduledTasks = [tasks valueForKey:@"scheduledDate"];
        scheduledTasks = [[[NSSet setWithArray:scheduledTasks] allObjects] sortedArrayUsingSelector:@selector(compare:)];

        NSMutableArray *shortTermTasks = [NSMutableArray array];
        NSMutableArray *midTermTasks = [NSMutableArray array];
        NSMutableArray *longTermTasks = [NSMutableArray array];

        for (NSDate *scheduledDate in scheduledTasks) {
            NSString *dateString = [NSString dateStringFromFullDate:scheduledDate];

            NSPredicate *pred = [NSPredicate predicateWithFormat:@"scheduledDate == %@", scheduledDate];
            NSManagedObject *task = [[tasks filteredArrayUsingPredicate:pred] lastObject]; 

            if ([[self shortTermDateStrings] containsObject:dateString]) {
                [shortTermTasks addObject:task];
            }
            if ([[self midTermDateStrings] containsObject:dateString]) {
                [midTermTasks addObject:task];
            }
            if ([[self longTermDateStrings] containsObject:dateString]) {
                [longTermTasks addObject:task];
            }
        }
        sectionsArray = [NSMutableArray arrayWithObjects:shortTermTasks,midTermTasks,longTermTasks, nil];
        return sectionsArray;
    }
    return [NSMutableArray array];
}

我研究并发现(NSFetchedResultsController *)fetchedResultsController定义了这些部分的组织方式,现在的问题是如何在这里生成我的自定义数组。

我的(NSFetchedResultsController *)fetchedResultsController样子是这样的:

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"scheduledDate" ascending:YES];
    NSArray *sortDescriptors = @[sortDescriptor];

    [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:nil cacheName:@"Master"];

    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
         // Replace this implementation with code to handle the error appropriately.
         // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _fetchedResultsController;
}    

更新:生成的代码shortTermmidTermlongTerm日期根据注意:我为此做[NSDate date]sectionIdentifier 很多NSDateNSString类别。

-(NSArray *)shortTermDates {
    NSArray *fullDateList = [NSDate daysFrom:[NSDate date] to:[NSDate dateWithDaysFromNow:2]];
    NSMutableArray *daysList = [NSMutableArray array];

    NSString *dateString = nil;
    for (NSDate *date in fullDateList) {
        dateString = [NSString dateStringFromFullDate:date];
        [daysList addObject:dateString];
    }
    return fullDateList;
}

-(NSArray *)shortTermDateStrings {
    NSMutableArray *daysList = [NSMutableArray array];

    NSString *dateString = nil;
    for (NSDate *date in [self shortTermDates]) {
        dateString = [NSString dateStringFromFullDate:date];
        [daysList addObject:dateString];
    }
    return daysList;
}

-(NSArray *)midTermDates {
    NSDate *startDate = [[self shortTermDates] lastObject];
    int addition = 5;
    int dayFromLastTermDate = [NSDate extractDayFromDate:[[self shortTermDates] lastObject]];
    NSDate *date = [NSDate dateWithYear:[NSDate extractYearFromDate:startDate] month:[NSDate extractMonthFromDate:startDate] day:dayFromLastTermDate+addition hour:[NSDate extractHourFromDate:startDate] minute:[NSDate extractMinuteFromDate:startDate] second:[NSDate extractSecondFromDate:startDate]];
    NSArray *fullDateList = [NSDate daysFrom:startDate to:date];
    return fullDateList;
}

-(NSArray *)midTermDateStrings {
    NSMutableArray *daysList = [NSMutableArray array];

    NSString *dateString = nil;
    for (NSDate *date in [self midTermDates]) {
        dateString = [NSString dateStringFromFullDate:date];
        [daysList addObject:dateString];
    }
    return daysList;
}

-(NSArray *)longTermDates {
    NSDate *startDate = [[self midTermDates] lastObject];
    int addition = 8;
    int dayFromLastTermDate = [NSDate extractDayFromDate:[[self midTermDates] lastObject]];
    NSDate *date = [NSDate dateWithYear:[NSDate extractYearFromDate:startDate] month:[NSDate extractMonthFromDate:startDate] day:dayFromLastTermDate+addition hour:[NSDate extractHourFromDate:startDate] minute:[NSDate extractMinuteFromDate:startDate] second:[NSDate extractSecondFromDate:startDate]];
    NSArray *fullDateList = [NSDate daysFrom:startDate to:date];
    return fullDateList;
}

-(NSArray *)longTermDateStrings {
    NSMutableArray *daysList = [NSMutableArray array];

    NSString *dateString = nil;
    for (NSDate *date in [self longTermDates]) {
        dateString = [NSString dateStringFromFullDate:date];
        [daysList addObject:dateString];
    }
    return daysList;
}

- (NSString *)sectionIdentifier;
{
    NSDate *date = self.scheduledDate;
    if ([date compare:[[self shortTermDates] lastObject]] == NSOrderedAscending) {
        return @"0";
        if ([date compare:[[self midTermDates] lastObject]] == NSOrderedAscending) {
            return @"1";
        } else {
            return @"2";
        }
    }
    return nil;
}
4

2 回答 2

3

使用获取结果控制器 (FRC) 将表视图分组到多个部分需要两件事:

  • 您必须sectionNameKeyPath:为 FRC 设置。这可以是实体的任何属性(持久或瞬态),甚至可以是托管对象子类的任意实例方法。
  • FRC 请求的第一个排序描述符必须将对象排序为与sectionNameKeyPath:属性/方法相同的相对排序。此排序描述符只能使用实体的持久属性。

您已经根据scheduledDate属性对对象进行了排序。要将对象分组为部分,您只需向托管对象子类添加一个“合适的”实例方法。

让我们假设您有一些日期变量shortTermLimitmidTermLimit. 然后,您可以在托管对象子类的类类别中定义以下方法:

@implementation Task (CategoryMethods)

- (NSString *)sectionIdentifier;
{
    NSDate *date = self.scheduledDate;
    if ([date compare:shortTermLimit] == NSOrderedAscending) {
        return @"0";
    } else if ([date compare:midTermLimit] == NSOrderedAscending) {
        return @"1";
    } else {
        return @"2";
    }
}

@end

然后使用参数创建 FRC

sectionNameKeyPath:@"sectionIdentifier"

现在所有之前调度的任务都shortTermLimit被归为“0”节,之前调度的任务midTermLimit被归为“1”节,剩余的任务被归为“2”节。

请注意,相对排序(“0”、“1”、“2”)与使用 的排序描述符兼容scheduledDate

但是您不希望将“0”、“1”、“2”作为节标题,所以剩下的就是修改titleForHeaderInSection委托方法:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    NSString *name = [sectionInfo name];
    if ([name isEqualToString:@"0"]) {
        return @"Short Term";
    } else if ([name isEqualToString:@"1"]) {
        return @"Mid Term";
    } else {
        return @"Long Term";
    }
}

还可以查看 Apple Developer Library 中的“DateSectionTitles”示例项目,它的工作原理类似于按年和月将对象分组到部分中。

于 2013-07-20T18:09:23.590 回答
0

Task向您的实体添加一个瞬态属性,将其命名为sectionName. 当实体保存或scheduledDate设置时,计算新的sectionName并存储它。设置sectionName为 FRC 使用的密钥路径。

于 2013-07-20T17:14:13.197 回答