2013-10-10 24 views
0

我有一個應用程序需要根據時間戳過濾對象。例如,假設我想過濾事件以僅顯示過去的事件。然後我想在UITableView中顯示它們。我會成立一個NSFetchedResultsController像這樣:使用當前時間的NSPredicate更新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

檢查未更改的數據更改嗎?那麼你的意思是你想在他們到期時刪除項目嗎? – Wain

+0

是或添加新的項目,落入搜索範圍。 –

+0

滾動導致的問題是什麼? –

回答

0

只有當物品時間不再有效時,才需要更改顯示的數據。它有一個日期,所以你可以計算未來的時間,並設置一個計時器。您需要定購數據,以便下一個要到期的項目總是列表中的第一個。

爲了方便,您可以在計時器到期時檢查滾動,並延遲重新加載直到滾動動畫完成。

+0

不幸的是,如果我提前計算下一個「到期」時間,那麼在新數據添加和刪除時它不會更新。 –

相關問題