如何在 Swift 4 中使用 FetchedResultsController 获取 DateSectionTitles

How to get DateSectionTitles using FetchedResultsController in Swift 4

我正在使用 FRC,我想创建根据日期 (DD MMMM) 对数据进行分组的部分!每个任务都有一个日期,我正在使用该日期并将其格式化为部分 header 标题。

我正在使用他们在 Objective C 中提供的 Apple 示例代码并将其转换为 swift。这是代码:

import UIKit
import CoreData

class completedNotes: NSManagedObject
{
    @NSManaged var cNote: String
    @NSManaged var cPriorityColor: UIColor
    @NSManaged var cDate: Date

}


extension completedNotes {
var sectionIdentifier : String? {
    // Create and cache the section identifier on demand.

    self.willAccessValue(forKey: "sectionIdentifier")
    var tmp = self.primitiveValue(forKey: "sectionIdentifier") as? String
    self.didAccessValue(forKey: "sectionIdentifier")

    if tmp == nil {
        if let timeStamp = self.value(forKey: "cDate") as? NSDate {
            /*
             Sections are organized by month and year. Create the section
             identifier as a string representing the number (year * 1000) + month;
             this way they will be correctly ordered chronologically regardless
             of the actual name of the month.
             */
            let calendar  = NSCalendar.current

            let components = calendar.dateComponents([.year, .month,], from: timeStamp as Date)
            tmp = String(format: "%ld", components.year! * 1000 + components.month!)
            self.setPrimitiveValue(tmp, forKey: "sectionIdentifier")
        }
    }
    return tmp
}
}

上面的代码在 NSManagedObject 中,我在其中创建了一个瞬态 属性 sectionIdentifier。它采用 cDate 的值,即 NSManagedObject。

然后在titlesforheaderinSection

 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    struct Formatter {
        static let formatter : DateFormatter = {
            let fmt = DateFormatter()
            let dateFormat = DateFormatter.dateFormat(fromTemplate: "MMMM yyyy", options: 0,
                                                      locale: NSLocale.current)
            fmt.dateFormat = dateFormat
            return fmt
        }()
    }

    if let theSection = fetchedResultsController1.sections?[section] as? NSFetchedResultsSectionInfo,
        let numericSection = Int(theSection.name) {
        var components = DateComponents()
        components.year = numericSection / 1000
        components.month = numericSection % 1000
        if let date = Calendar.current.date(from: components) {
            let titleString = Formatter.formatter.string(from: date)
            return titleString
        }
    }
    return nil

}

这是我用于其他表格视图功能的代码:

func numberOfSections(in tableView: UITableView) -> Int {
    return (fetchedResultsController1.sections?.count)!
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController1.sections![section].numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath) as! TasksTableViewCell
    cell.selectionStyle = .none

    cell.textview.text = fetchedResultsController1.object(at: indexPath).cNote
    cell.priorityline.backgroundColor = fetchedResultsController1.object(at: indexPath).cPriorityColor

    return cell
}

这是 NSFetchedResultsController:

let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.moContext1, sectionNameKeyPath: "sectionIdentifier", cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController as? NSFetchedResultsController<completedNotes>

为什么我无法在 tableview 中显示任何部分,为什么当我删除最后一个 tableview 单元格时,应用程序崩溃了?

谢谢!

传递给 sectionNameKeyPath: 的关键路径 获取的结果控制器的参数必须对 Objective-C 运行时。在 Swift 4 中需要显式注释 与 @objc(也比较 ):

extension completedNotes {
    @objc var sectionIdentifier : String? { 
        // ...
    }
}

否则,部分名称键路径将被静默忽略。