我有一個應用程序需要根據時間戳過濾對象。例如,假設我想過濾事件以僅顯示過去的事件。然後我想在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
一次,但是如果用戶在表格中滾動會導致問題。有沒有更好的方法來檢查數據是否發生了變化?由於數據沒有變化,我不能依賴任何保存事件。
檢查未更改的數據更改嗎?那麼你的意思是你想在他們到期時刪除項目嗎? – Wain
是或添加新的項目,落入搜索範圍。 –
滾動導致的問題是什麼? –