首页 > 解决方案 > Swift NSFetchedResultsController 不基于 sectionNameKeyPath 进行分段

问题描述

lazy var fetchedResultsController: NSFetchedResultsController<StoryTemplatePack> =
    {
        let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

        var frc: NSFetchedResultsController<StoryTemplatePack> = NSFetchedResultsController(fetchRequest: self.createFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "sectionnum", cacheName: nil)
        frc.delegate = self

        return frc
}()

// FetchedResultsController: Create Request
func createFetchRequest() -> NSFetchRequest<StoryTemplatePack> {
    let fetchRequest = NSFetchRequest<StoryTemplatePack>(entityName: "StoryTemplatePack")

    fetchRequest.predicate = NSPredicate.init(format: "productidentifier != nil")

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: "isfeatured", ascending: false),
        NSSortDescriptor(key: "ispurchased", ascending: true),
        NSSortDescriptor(key: "name", ascending: true)
    ]


    return fetchRequest
}

应根据sectionnumStoryTemplatePack 上的属性(这是在代码中计算的瞬态属性)对结果进行分段。

当我遍历 NSFetchedResultsController 的结果时,它会显示正确的部分编号和故事包名称。应该有 3 个部分,但 FRC 只报告 1 个部分。转储的结果还表明我正确地对结果进行了排序,以便部分值单调增加。

---- dumping frc, num sections: 1
    section 0 pack Incredible Journeys
    section 0 pack Out for a Date
    section 0 pack Party Time
    section 1 pack Holiday Craziness
    section 1 pack In the Office
    section 1 pack On the Internets
    section 1 pack On the Job
    section 1 pack School Daze
    section 1 pack Social Networking
    section 1 pack TV Troubles
    section 1 pack Technology Takes Over
    section 2 pack Christmas Shenanigans
---- done dumping

self.fetchedResultsController.sections!.count当它应该返回 3 时返回 1。

我做错了什么或错过了什么?

标签: iosswiftnsfetchedresultscontroller

解决方案


推荐阅读