【发布时间】:2015-05-05 19:00:18
【问题描述】:
我在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 并重新加载 托管文档完成打开后的表格视图 (注释掉代码)。这并没有改变任何东西。
- 我检查了
UIManagedDocument变量,它包含正确的值。 - 基础 SQL 数据库包含有效值。
我的问题
您对我的代码返回的节数为何为零有任何想法或建议吗?
【问题讨论】:
-
控制器真的创建了吗?不确定您是否可以使用这样的本地化比较选择器...
-
@Wain:是的,控制器已创建。即使我不使用本地化比较选择器,它也不起作用。
-
您如何验证商店中有物品?
-
@Wain:我使用 SQLite 工具检查了数据库。
标签: ios objective-c core-data nsfetchedresultscontroller uimanageddocument