0

我是核心数据和 NSFetched 结果控制器的新手。到目前为止,我设法填满了我的 tableView。但现在我想分成几个部分。这是我的代码的样子。

- (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 中做什么 我正在使用包含 6 个图像视图的自定义 tableviewCell。但是一行可能只包含 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 ++;
    }
4

1 回答 1

0

使用该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 函数。

于 2012-10-10T22:49:35.330 回答