我有一个属性为“组”的实体,因为我想按“组”(0 或 1)将我的实体列表分成两部分
@property (nonatomic, retain) NSNumber * group;
在我的 fetchedResultsController 中,我将 sectionNameKeyPath 指定为“group”
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"group" cacheName:nil];
如何在下面的方法中返回每个部分的行数?我收到以下错误:
Terminating app due to uncaught exception 'NSRangeException', reason:
'-[__NSArrayM objectAtIndex:]: index 1 beyond bounds for empty array'
代码如下:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section]
numberOfObjects];
}
我也试过这个,得到了同样的错误:
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]
objectAtIndex:section];
return [sectionInfo numberOfObjects];
请注意,我也实现了这个方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
最佳答案
您是否实现了numberOfSectionsInTableView:
?如果您不实现它,tableView 会假定您有 1 个部分,如果 fetchedResultsController 没有任何部分(即它没有对象),这将导致此异常。
您必须在 numberOfSectionsInTableView:
中返回 [sections count]
。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.fetchedResultsController.sections count];
}
如果你总是想显示两个部分,你必须检查 fetchedResultsController 是否有请求的部分。如果 fetchedResultsController 没有这个部分,不要向它询问此操作中的对象数。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger count = 0;
NSInteger realNumberOfSections = [self.fetchedResultsController.sections count];
if (section < realNumberOfSections) {
// fetchedResultsController has this section
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController.sections objectAtIndex:section];
count = [sectionInfo numberOfObjects];
}
else {
// section not present in fetchedResultsController
count = 0; // for empty section, or 1 if you want to show a "no objects" cell.
}
return count;
}
如果您在 else 中返回 0 以外的值,您还必须更改 tableView:cellForRowAtIndexPath:
。与此方法类似,您必须检查 fetchedResultsController 是否在请求的 indexPath 处有一个对象。
关于ios - 如何使用 sectionNameKeyPath 从 NSFetchedResultsController 获取 numberOfRowsInSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343346/