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

4

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

我正在使用苹果在Objective C中提供的示例代码,并将其转换为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的值,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>

为什么表格视图中没有任何部分显示,并且当我删除最后一个表格视图单元格时,应用程序会崩溃?

谢谢!


我这里没有使用故事板。只是代码! - Osama Naeem
不!不使用.grouped样式属性。 - Osama Naeem
我是这样创建表格视图的:let tableView: UITableView = { let tv = UITableView() tv.separatorColor = .clear return tv }() - Osama Naeem
1个回答

2
传递给获取结果控制器的sectionNameKeyPath:参数的关键路径必须对Objective-C运行时可见。在Swift 4中,这需要使用@objc进行显式注释(还可以比较如何处理Swift 4中#selector()中@objc推断停用?):
extension completedNotes {
    @objc var sectionIdentifier : String? { 
        // ...
    }
}

没有这个,章节名称的键路径将被静默忽略。

非常感谢,它起作用了!!只有一个问题,当我删除部分中的最后一个单元格时,应用程序会崩溃。为什么会这样?我应该使用sectiondidchange frc方法吗? - Osama Naeem
@OsamaNaeem:是的,你需要实现所有 FRC委托方法。 - Martin R
@OsamaNaeem:顺便说一下,你的获取请求也应该在键“cDate”上有一个排序描述符。 - Martin R
@Martin_R 嘿 Martin,我想知道如何将日期格式从“MMMM yyyy”更改为“dMMMM”,以便根据日期和月份创建部分。就像这样-> 3月26日。 - Osama Naeem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接