我有一个需要根据时间戳过滤对象的应用程序。例如,假设我想过滤一个事件以仅显示过去的事件。我想在UITableView中显示它们。我会像这样设置一个NSFetchedResultsController:
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" 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:@"timeStamp" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
// Filter based on only time stamps in the past
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timeStamp < %@", [NSDate date]];
fetchRequest.predicate = predicate;
[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:nil];
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;
}
我的问题是:更新此视图的最佳方法是什么,以便过滤器基于当前时间?我现有的解决方案是建立一个这样的方法:
- (void)updateFetchedResultsController {
self.fetchedResultsController = nil;
[self.tableView reloadData];
}
然后我在viewWillAppear:
或viewDidAppear:
上调用该方法。除非用户在屏幕上停留一段时间,否则这种情况有效。
我也可以使用NSTimer
并每分钟调用updateFetchedResultsController
一次,但如果用户滚动表格会导致问题。有没有更好的方法来检查数据是否已更改?由于数据没有变化,我不能依赖任何保存事件。
答案 0 :(得分:0)
当项目时间不再有效时,您只需要更改显示的数据。它有一个日期,因此您可以计算未来的时间并设置计时器。您订购数据,以便下一个到期的项目始终是列表中的第一个。
要精致,您可以在计时器到期时检查滚动并延迟重新加载,直到滚动动画完成。