【问题标题】:Core Data fetchedresultscontroller question : what is "sections" for?Core Data fetchedresultscontroller 问题:什么是“部分”?
【发布时间】:2010-05-11 08:46:05
【问题描述】:

我正在尝试了解 Core Data(我是 iPhone 开发的菜鸟),为了做到这一点,我试图从 fetchedresultscontroller 和 NSlog 中获取一个对象,它的名称(对象的属性)。我试着这样做:

NSArray *ar = [NSArray arrayWithArray:[fetchedResultsController sections]];
Task *t = [ar objectAtIndex:0];
NSLog(@"%@", t.taskName);

但是,应用程序因此错误而崩溃:应用程序因错误而崩溃

由于未捕获而终止应用 例外 'NSInvalidArgumentException',原因: '*** -[_NSDefaultSectionInfo taskName]:发送了无法识别的选择器 到实例 0x3d1f670'

从那以后,我了解到您需要为此使用 fetched objects 属性,但是节是做什么用的?感谢您的帮助,对不起,如果这是一个非常愚蠢的问题。我查看了文档,但仍然不明白。

【问题讨论】:

    标签: iphone objective-c cocoa-touch core-data


    【解决方案1】:

    NSFetchedResultsController 可以根据您指定的键将您的对象分组到多个部分。因此,例如,如果您的实体具有 category 属性,您可以按 category 对对象进行分组,并将它们显示在该类别的标题下。

    每个UITableView(和每个NSFetchedResultsController)都至少包含一个部分,因此即使您不使用此功能,您仍然需要处理部分。如果您check the documentation,您将看到sections 属性中的对象符合NSFetchedResultsSectionInfo 协议,该协议具有包含该部分中的对象的objects 属性。

    有两种方法可以从NSFetchedResultsController 中获取实际对象:

    id <NSFetchedResultsSectionInfo> sectionInfo = [fetchedResultsController.sections objectAtIndex:0];
    Task *task = [sectionInfo.objects objectAtIndex:0];
    

    另一种更简单且首选的方法是使用objectAtIndexPath: 方法。

    Task *task = [fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    

    这两个样本是等价的。 UIKit adds some methods to NSIndexPath 使使用表视图和获取结果控制器更容易。另外,请注意UITableViewDataSource 和UITableViewDelegate 方法都为您提供NSIndexPath 对象,因此您通常可以将这些传递给objectAtIndexPath: 以获得该单元格的正确对象。

    Apple 还提供了decent tutorial 在 iPhone 上使用 Core Data。它会回答你的很多问题。不幸的是,它没有深入介绍NSFetchedResultsController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      相关资源
      最近更新 更多