swift - CoreData 实体和属性

标签 swift uitableview core-data uitableviewsectionheader

我是 swift 的新手,我刚刚了解了核心数据,我正在尝试在我目前正在从事的项目中实现它。

之前我正在接受一个结构

struct Course : Decodable {
let CourseName : String;
let Requirements : String;
}

struct  AllCourses : Decodable {
let ProgramName : String
let Courses : [Course]
}

我尝试创建两个实体并创建父子关系,我设法保存了它们,但是当我使用节标题执行 TableView 时,我不能因为没有嵌套数组。

如果我想要一个带有程序名称的部分,我的属性和实体会怎样。

最佳答案

这是将 NSFetchResultsController 与您的 UITableViewController 结合使用的绝佳机会。

假设你的模型有这样的东西:

Core Data Entity Model

你的代码看起来像这样:

import UIKit
import CoreData

class ViewController: UITableViewController {

    lazy var fetchedResultsController: NSFetchedResultsController<Course> =    {
        let fetchRequest = NSFetchRequest<Course>(entityName: "Course")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "program.name", ascending: true)]

        let moc = *your context*

        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "program.name", cacheName: nil)
        // controller.delegate = self

        return controller
    }()

    override func numberOfSections(in tableView: UITableView) -> Int {
        guard let sections = self.fetchedResultsController.sections else {
            return 0
        }

        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let sections = self.fetchedResultsController.sections else {
            return 0
        }

        return sections[section].numberOfObjects
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        guard let sections = self.fetchedResultsController.sections else {
            return ""
        }

        return sections[section].indexTitle
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell") as! UITableViewCell
        cell.course = self.fetchedResultsController.object(at: indexPath)
        return cell
    }
}

当您向获取的结果 Controller 提供 sectionNameKeyPath 时,它会自动对结果进行“分组”。您可以通过在 Controller 上使用谓词来进一步限制结果。

关于swift - CoreData 实体和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039381/

相关文章:

ios - Admob 横幅广告最佳实践

ios - 在 Swift 中使用动画将按钮从一个 UITableViewCell 移动到另一个

iphone - 逐行 2 列的表格 View ,iphone/ipad

ios - 核心数据迁移技术 : moving attribute -> modelled relationship

json - 使用Swift从YouTube API解析JSON响应

swift - 如何使用 UIViewControllerRepresentable 在 SwiftUI 中呈现 UICollectionView

ios - 如何在 Swift 中将 CMutablePointer<ObjCBool​​> 设置为 false?

ios - 如何将图像设置为在另一个viewController中异步获取的UIImageView?

ios - 在 Core Data 上创建关键字结构并搜索那个大动物

ios - 核心数据 - 以多对多关系访问实例与获取请求?