0

我有一个需要根据时间戳过滤对象的应用程序。例如,假设我想过滤一个事件以仅显示过去的事件。然后我想在 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:然后我在or上调用该方法viewDidAppear:。除非用户在屏幕上停留一段时间,否则此方法有效。

我也可以每分钟左右使用一次NSTimerand 调用updateFetchedResultsController,但是如果用户滚动表格,这会导致问题。有没有更好的方法来检查数据是否已更改?由于数据没有改变,我不能依赖任何保存事件。

4

1 回答 1

0

仅当项目时间不再有效时,您才需要更改显示的数据。它有一个日期,因此您可以计算未来多长时间并设置一个计时器。您对数据进行排序,因此下一个要过期的项目始终是列表中的第一个。

为了巧妙,您可以在计时器到期时检查滚动并延迟重新加载,直到滚动动画完成。

于 2013-10-10T23:11:19.163 回答