ios - 我如何从 CoreData 关系设置 UItableView 数据源。

标签 ios swift uitableview core-data

我的核心数据关系提取请求返回 NSSet 对象。自从无序集中的 NSset 以来,如何为 TableView 数据源设置此数据。我可以将 NSSet 转换为 NSArray ,但它会以相同的顺序返回数据。

最佳答案

Apple is clear “数组中对象的顺序未定义。”所以我希望它会改变。

我建议您将 allObjects 数组存储到一个实例变量中,并使用它来实现 numberOfSectionsInTableView() 和其他数据源方法。

您还可以将您的 NSFetchedResultsController 存储在实例变量中并安全地使用它,例如:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rows = 0
    if self.fetchedResultsController!.sections!.count > 0 {
        let sectionInfo = getSectionInfo(section)
        rows = sectionInfo!.numberOfObjects
    }
    return rows
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let sectionInfo = getSectionInfo(section)
    return sectionInfo!.name
}

func getSectionInfo(section: Int) -> NSFetchedResultsSectionInfo? {
    var sections: [AnyObject] = self.fetchedResultsController!.sections!
    if section < sections.count {
        let x = sections[section] as! NSFetchedResultsSectionInfo
        return x
    }
    return nil
}

override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    return self.fetchedResultsController!.sectionForSectionIndexTitle(title, atIndex: index)
}

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return self.fetchedResultsController!.sectionIndexTitles
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier")! as UITableViewCell

    // Use your own NSManagedObject class here...mine is Category
    let category = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Category
    return cell
}

就我个人而言,我已将上述所有方法编码到我重用的基类中,这样我就可以在每个新 TableView 中实现 cellForRowAtIndexPath()。我发了a copy on github以防对其他人有用。

关于ios - 我如何从 CoreData 关系设置 UItableView 数据源。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631763/

相关文章:

ios - 在 iOS 中将条码扫描器作为键盘的方法?

iOS8 无法在应用程序组共享容器位置下创建文件夹/文件

swift - 如何为等待函数调用添加超时

ios - 具有清晰背景的 UISlider 拇指图像在其后面显示轨道

ios - 如何在闭包中访问类的变量?

Swift:当动态更改节标题高度时,UITableView 滚动回顶部

ios - 无法在 IOS7 中重新加载 TableView

ios - 在 iOS sdk 中下载图片的多任务处理

ios - 在 iPhone XS 上使用 ARKit2 和 Vision (VNDetectFaceRectanglesRequest) 时如何修复 IOAF 代码 GPU 错误

ios - 无法在 UIWebView 中播放 Youtube 视频(iOS、Swift)