使用 NSFetched 结果控制器和部分



我是核心数据和NSFetched resultcontroller的新手。到目前为止,我设法填满了我的表视图。但现在我想分成几个部分。这是我的代码的样子。

- (void)getKeepers // attaches an NSFetchRequest to this UITableViewController
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Team"];
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"sortOrder" ascending:YES]];
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.genkDatabase.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
}

让我概述一下情况。我正在为一家足球俱乐部制作应用程序。在我的表格视图中,我希望每个位置(守门员,后卫,边锋,前锋)都有一个新的部分。我的核心数据库如下所示。

- TEAM
   -name
   -Position
   -img_url
   -birthDate
   -sortOrder

我添加了属性 sortOrder 来对我的玩家进行排序。但是谁能帮我把它分成几个部分?

提前感谢!!

我在CELL_FOR_ROW_AT_INDEX里做什么在我的cellForRowAtIndex中,我正在做不平常的事情。我正在使用包含 6 个图像视图的自定义表视图单元格。但一行可能只包含 4 张图像。你可以看到我在这里想做什么。

#define IMAGES_PER_ROW  6
   NSInteger frcRow = indexPath.row * IMAGES_PER_ROW; // row in fetched results controller
    for (int col = 1; col <= IMAGES_PER_ROW; col++) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:frcRow inSection:0];
        Team *team = [self.fetchedResultsController objectAtIndexPath:path];
        NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:team.image]];
        UIImage *image;
        if (imgData == nil) {
            // default image
            image = [UIImage imageWithContentsOfFile:@"keeperNil.jpg"];
        } else {
            image = [UIImage imageWithData:imgData];
        }
        [cell setImage:image forPosition:col];
        frcRow ++;
    }

使用sectionNameKeyPath值作为要用于部分的字段。

然后你需要这三个功能...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.fetchedResultsController.sections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = self.fetchedResultsController.sections[section];
    return [sectionInfo numberOfObjects];
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = self.fetchedResultsController.sections[section];
    return [sectionInfo name];
}

这应该足够了。

您的cellForRowAtIndexPath函数应该看起来像这样...

...
UITableViewCell* cell = [UITableViewCell dequeueCellWithReuseIdnetifier:@"blah"];
Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = team.name;
cell.detailTextLabel.text = team.position.

或类似的东西。

收到的错误意味着您正在尝试访问不包含足够条目的数组。

如果这不起作用,则发布您的cellForRowAtIndexPath函数。

最新更新