sectionNameKeyPath NSFetchedResultsController被忽略 - Swift

时间:2017-06-12 21:48:46

标签: ios core-data nsfetchedresultscontroller

我遵循了这个建议: Format sectionNameKeyPath NSFetchedResultsController - Swift

我对此实现有点问题。 使用Xcode 8和iOS 10。

我将Codegen设置为Manual / None并添加了我的NSManagedObject子类。

然后我按你的建议添加:

var sectionIdentifier: String
{
    get
    {
        let dateFormatter = DateFormatter()
        // dateFormatter.dateStyle = .short
        // dateFormatter.timeStyle = .none
        // ..or to stick to your original question:
        dateFormatter.dateFormat = "yyyy-MMM-dd"
        return dateFormatter.string(from: date! as Date)
    }
}

但无论出于何种原因,它都会被sectionNameKeyPath忽略。当我进入" date"在sectionNameKeyPath中,我得到与上面提到的AllReadyHome相同的结果。

我甚至尝试过:

return (date?.description)!

它没有产生任何结果。

也许有人可以指出我正确的方向......

更新1: 这就是我的fetchedResultsController的样子:

let fetchRequest: NSFetchRequest<Time> = Time.fetchRequest()
    fetchRequest.fetchBatchSize = 20
    let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "sectionIdentifier", cacheName: "Time")

结果:没有部分 No Sections

使用日期时,这是我的实体的属性:

let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "date", cacheName: "Time")

看起来像这样: Sections

更新2: 当按照建议使用sortDescriptor时,我会崩溃(&#34; sectionIdentifier不在实体中):

let fetchRequest: NSFetchRequest<Time> = Time.fetchRequest()
    fetchRequest.fetchBatchSize = 20
    let sortDescriptor1 = NSSortDescriptor(key: "sectionIdentifier", ascending: false)
    let sortDescriptor2 = NSSortDescriptor(key: "date", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "sectionIdentifier", cacheName: "Time")

更新3: 到屏幕时我收到以下警告:

A section returned nil value for section name key path 'sectionIdentifier'. Objects will be placed in unnamed section
 CoreData: error: (NSFetchedResultsController). A section returned nil value for section name key path 'sectionIdentifier'. Objects will be placed in unnamed section

2 个答案:

答案 0 :(得分:0)

将@objc用于sectionIdentifier

示例:

@objc var sectionIdentifier: String {
    get {
        return ""
    }
}

答案 1 :(得分:0)

不可能将瞬态变量或计算变量用作sectionNameKeyPath

解决方法是将sectionIdentifier声明为extension Date

extension Date {
    var sectionIdentifier: String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MMM-dd"
        return dateFormatter.string(from: self)
    }
}

然后创建第一个排序描述符

let sortDescriptor1 = [NSSortDescriptor(key: "date.sectionIdentifier", ascending: false)