我在NSFetchedResultsController
内使用UITableViewController
。
不幸的是,[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;
}
UIManagedDocument
变量,它包含正确的值。您是否有任何想法或建议为什么我的代码返回的部分数为零?
答案 0 :(得分:1)
您需要在获取的结果控制器方法中调用performFetch
。