【问题标题】:How to get one record per section when using NSFetchedResultsController使用 NSFetchedResultsController 时如何获取每个部分的一条记录
【发布时间】:2014-11-13 11:41:37
【问题描述】:

我正在开发一个使用 Core Data 的 iOS 应用程序,我想使用 UITableView 显示一个实体。

为此,我正在使用 NSFetchedResultsController。 我想要实现的目标是在其部分中显示每条记录。基本上我想要每节 1 行。

我正在努力的方法是:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

因为我想在计算numberOfSectionsInTableView的时候有这段代码:

{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

并且我想在计算 numberOfRowsInSection 时使用return 1(显然我不能将indexPath.section传递给numberOfSectionsInTableView)。 在这个问题/情况下的方法是什么?谢谢。

【问题讨论】:

    标签: ios uitableview core-data nsfetchedresultscontroller nsfetchrequest


    【解决方案1】:

    嗯,

    显然,您将拥有与对象一样多的部分:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        return self.fetchedResultController.fetchedObjects.count;
    }
    

    那么,你将只有一行/一节,因为这是你想要的

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
       return 1;
    }
    

    然后在 cellForRowAtIndexPath 中使用 indexPath.section 作为 rowIndex,使用 indexPath.row 作为 sectionIndex。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSIndexPath * correctedIP = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
    
        id myItem =  [self.fetchedResultController objectAtIndexPath: correctedIP];
    /* ... */
    
    }
    

    【讨论】:

    • 更正后的 IP 不应交换行和节。它应该对行使用section,对部分使用0。是的,它可能总是为零,但最好明确地做到这一点。
    • 它按预期工作。非常感谢@Fogmeister 和 Florian Burel 的快速和正确回复。你太棒了。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2022-10-14
    • 2022-07-08
    • 2019-06-23
    • 2014-06-01
    相关资源
    最近更新 更多