TableView分段排序下一个过期



所以我正在做一个小的待办事项应用程序。TableView显示了一个CoreData实体,它具有名称(string)和日期(Date)的属性。目前NSfetchedResultsController排序表视图的日期的待办事项,但我也想要一些部分,例如"过期的待办事项-其中有一个过去的日期"或"下周的待办事项"

我怎样才能做到这一点?

代码NSFetchedResultsController:

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    // Create and configure a fetch request with the Book entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Inventory" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Create the sort descriptors array.
    NSSortDescriptor *productDescriptor = [[NSSortDescriptor alloc] initWithKey:@"inventoryProductName" ascending:YES];
    NSSortDescriptor *dateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"expireDate" ascending:YES];
    NSArray *sortDescriptors = @[dateDescriptor,productDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    // Create and initialize the fetch results controller.
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"inventoryProductName" cacheName:@"Root"];
    _fetchedResultsController.delegate = self;
    return _fetchedResultsController;
}

代码TableView:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
    return [sectionInfo numberOfObjects];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    Inventory *inventory = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = inventory.inventoryProductName;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    NSDate *dt = inventory.expireDate;
    NSString *dateAsString = [formatter stringFromDate:dt];
    //[formatter release];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Expires at: %@", dateAsString];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

您需要给todo项另一个属性来反映您想要的内容。至于"过去"、"下周",你可以使用一个瞬态属性,它是通过自定义getter动态计算出来的。在某些情况下,你将不得不把它持久化为一个(非瞬态)属性,以使你获取的结果控制器工作。

对于可预测的排序,实际的属性值可以只是一个数字—这将允许您还包含与日期无关的类别,例如"已取消"、"无效"等。

最新更新