如果我有两种不同的单元格,如何使用FetchedResultsController?

时间:2013-04-05 20:15:27

标签: ios objective-c uitableview core-data nsfetchedresultscontroller

我在IB中有一个原型tableview,它有两种不同的单元格:一个完整​​的单元格和一个基本单元格(用于显示文章,我根据它的文章类型使用每个文章)。

我想将FetchedResultsController集成到我的应用程序中,因此我可以使用CoreData填充tableview,但之前(使用NSArray而不是FetchedResultsController)我按如下方式处理了单元格设置:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = indexPath.row;
    static NSString *CellIdentifier = nil;
    Article *article = self.articles[row];

    // Checks if user simply added a body of text (not from a source or URL)
    if (article.isUserAddedText) {
        CellIdentifier = @"BasicArticleCell";
    }
    else {
        CellIdentifier = @"FullArticleCell";
    }

    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // If the user simply added a body of text, only articlePreview and progress has to be set
    cell.articlePreview.text = article.preview;
    cell.articleProgress.text = [self calculateTimeLeft:article];

    // If it's from a URL or a source, set title and URL
    if (!article.isUserAddedText) {
        cell.articleTitle.text = article.title;
        cell.articleURL.text = article.URL;
    }

    return cell;
}

但是现在我不知道如何检查它是否是基本文章(就像之前我在NSArray中检查了Article对象的属性一样)。我看到的一篇文章就是这样做的:

- (UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Set up the cell...
    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

但在我决定单元格标识符之前,我需要知道它是什么类型的文章,所以我不知道如何在这里做到这一点。我是否能够尽早获取FetchedResultController对象,查询它以查看文章属性的值是什么(无论它是否是基本属性)并相应地设置CellIdentifier?或者我还应该做些什么呢?

TL; DR:在使用FetchedResultsController时,如何根据要在单元格中显示的对象类型来决定CellIdentifier。

2 个答案:

答案 0 :(得分:1)

从fetchedResultsController检索对象时,可以检查类型,然后根据返回的内容确定要创建的单元格类型。例如:

id result = [fetchedResultsController objectAtIndexPath:indexPath];
if ([result isKindOfClass:[MyObject class]]) {
   // It's a MyObject, so create and configure an appropriate cell
} else ...

答案 1 :(得分:1)

在检索Article看起来有点不同之前,您可以使用与您所做的完全相同的逻辑

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  Article *article = [self.fetchedResultsController objectAtIndexPath:indexPath];

  NSString *CellIdentifier = [article isUserAddedText] ? @"BasicArticleCell" : @"FullArticleCell";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  // Set up the cell...
  [self configureCell:cell atIndexPath:indexPath];

  return cell;
}
相关问题