我有一个包含 8000 多个条目的大型数据库。我想加载并列出tableview
. 我用过NSFetchedResultsController
。除了性能不佳外,它工作正常。我在这里找到了教程
并在方法中添加了我performFetch:
的viewDidLoad:
方法。但是加载视图需要 2-3 秒。
这是我的代码。
- (void)loadFetchResultsController {
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Error occurs while fetching the foods with fetch results controller %@, %@", error, [error userInfo]);
exit(-1);
}
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (isSearching)
{
[NSFetchedResultsController deleteCacheWithName:@"SearchResults"];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Food" inManagedObjectContext:_managedObjectContext];
NSPredicate *hiddenPredicate = [NSPredicate predicateWithFormat:@"hidden == %@",[NSNumber numberWithBool:NO]];
if (isSearching)
{
hiddenPredicate = [NSPredicate predicateWithFormat:@"(hidden == %@) AND (name contains[cd] %@ OR foodDescription contains[cd] %@)",[NSNumber numberWithBool:NO], searchTerm,searchTerm];
}
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:hiddenPredicate];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:@"name.stringGroupByFirstInitial" cacheName:(isSearching) ? @"SearchResults" : @"Root"];
_fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
我使用了工具,发现调用 performFetch: 方法是在viewDidLoad:
调用时第一次加载整个数据。
我的food
数据模型是这样的:
任何提高性能和摆脱延迟的想法..任何帮助将不胜感激。