ios - 如何使用 sectionNameKeyPath 从 NSFetchedResultsController 获取 numberOfRowsInSection

标签 ios uitableview core-data nsfetchedresultscontroller

我有一个属性为“组”的实体,因为我想按“组”(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/

相关文章:

ios - 临时分发设备 - 每个应用程序还是每个开发人员?

ios - 我从我的 mac 中删除了所有 IOS 模拟器,现在我无法添加任何一个

iphone - 推送通知是否需要服务器?

ios - 在 iOS XCode 项目中管理大量目标预处理器宏

objective-c - 将 UITableViewController 添加到其他 View

objective-c - 在 uitableviewcell 中制作一个 "load more"按钮?

java - 在 javafx TableView 单元格中编辑数字

ios - 基于对多关系中的属性检索 NSManagedObject 的最快方法

ios - 核心数据-获取对象

ios - AND 和 OR 与 NSPredicate 结合。 iOS swift