所以我正在开发一款小巧的ToDo应用程序。 TableView显示了一个CoreData实体,其中包含名称(字符串)和日期(日期)的属性。 目前NSfetchedResultsController按ToDo的日期对tableView进行排序,但我也想要一些部分,例如“过期ToDo的 - 过去有一个日期”或“下周的ToDo”
我怎样才能做到这一点?
代码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;
}
Code 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;
}
答案 0 :(得分:0)
你需要给你的待办事项另一个反映你想要的东西。对于“过去”,“下周”,您可以使用通过自定义getter动态计算的瞬态属性。在某些情况下,您必须将此实际持久化为(非瞬态)属性,以使获取的结果控制器起作用。
对于可预测的排序,实际属性值可能只是一个数字 - 这将允许您还包括与日期无关的类别,例如“已取消”,“无效”等。