我在 UITableViewController
中使用 NSFetchedResultsController
。
不幸的是,[self.fetchedResultsController.sections count]
返回了一个不正确的值 0。它应该返回 1 个部分:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numberOfSections = [self.fetchedResultsController.sections count];
return numberOfSections;
}
这是我用来实例化 NSFetchedResultsController
并加载结果的代码:
@interface SearchQueryViewController ()
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property Search *selectedSearch;
@end
@implementation SearchQueryViewController
- (void)viewWillAppear:(BOOL)animated
{
if (!self.managedDocument) {
[[MyDocumentHandler sharedDocumentHandler] performWithDocument:^(UIManagedDocument *document) {
self.managedDocument = document;
// Uncommenting the following code lines does not change the outcome:
/*self.fetchedResultsController = nil;
[self.tableView reloadData];*/
}];
}
[super viewWillAppear:animated];
}
# pragma Fetched Results Controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController) return _fetchedResultsController;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Search"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"query" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request managedObjectContext:self.managedDocument.managedObjectContext
sectionNameKeyPath:nil cacheName:nil];
return _fetchedResultsController;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numberOfSections = [self.fetchedResultsController.sections count];
return numberOfSections;
}
// THIS IS NEVER BEING CALLED BECAUSE NUMBER OF SECTIONS IS RETURNED AS ZERO:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSInteger numberOfRows = [sectionInfo numberOfObjects];
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
Search *search = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = search.query;
return cell;
}
我尝试过的:
- 我尝试将 FetchedResultsController 设置为 nil 并重新加载 托管文档完成打开后的表格 View (注释掉代码)。这并没有改变任何东西。
- 我已经检查了
UIManagedDocument
变量,它包含正确的值。 - 底层 SQL 数据库包含有效值。
我的问题
为什么我的代码返回的部分计数为零,您有什么想法或建议吗?
最佳答案
您需要在抓取结果 Controller 方法中调用 performFetch
。
关于ios - 获取的结果 Controller 返回部分数 = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30061116/