ltsController获取DateSectionTitles

ltsController获取DateSectionTitles

本文介绍了如何在Swift 4中使用FetchedResultsController获取DateSectionTitles的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using FRC and I want to create sections that groups data according to date (DD MMMM)! Each task has a date and i am using that date and formatting it for the section header titles.

我正在使用他们在目标C中提供并转换的Apple示例代码它迅速。这是代码:

I am using Apple's sample code that they have provided in Objective C and converted it in to swift. Here is the code:

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。

The above code is in NSManagedObject where I am creating a transient property sectionIdentifier. It takes value of cDate which is 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

}

这是我的代码用于其他tableview函数:

This is the code I am using for other tableview functions:

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:

This is NSFetchedResultsController:

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

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

谢谢!

推荐答案

传递给 sectionNameKeyPath:
自变量结果控制器的参数的键路径必须对
Objective-C可见运行。在Swift 4中,需要使用 @objc 的显式注释
(也请比较):

The key path passed to the sectionNameKeyPath:argument of the fetched results controller must be visible to theObjective-C runtime. In Swift 4 that requires an explicit annotationwith @objc (compare also How can I deal with @objc inference deprecation with #selector() in Swift 4?):

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

没有那部分名称的键路径会被静默忽略。

Without that, the section name key path is silently ignored.

这篇关于如何在Swift 4中使用FetchedResultsController获取DateSectionTitles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!