在swift中用NSFetchedResultsController对核心数据进行分组。

问题描述 投票:3回答:3

我正在使用NSFetchedResultsController显示核心数据。下面是我的CoreData类

class Item: NSManagedObject {
    @NSManaged var category: String
    @NSManaged var dateAdded: NSDate
    @NSManaged var image: String
    @NSManaged var name: String
    @NSManaged var subCategory: String
}

我想将所有的项目分组显示。项目将根据dateAdded的月份进行分组。也就是说,部分标题将显示月份,而行将显示该月份添加的项目。

下面是我的NSFetchedResultsController的代码。

var fetchedResultsController: NSFetchedResultsController = {
    let fetchRequest = NSFetchRequest(entityName: "Item")

    let sort = NSSortDescriptor(key: "dateAdded", ascending: false)
    fetchRequest.sortDescriptors = [sort]

    fetchRequest.fetchBatchSize = 20

    let result = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.appDelegate.childManagedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
    result.delegate = self

    return result
}()

如何才能实现这个目标。任何帮助将被感激。

先谢谢你

swift core-data nsfetchedresultscontroller
3个回答
2
投票

最简单的方法是添加一个属性 dateAddedMonth 储存你的 NSDate 只与月份有关。然后您可以设置 sectionNameKeyPath"dateAddedMonth".


8
投票

我解决了它,因为

class Item: NSManagedObject {
    @NSManaged var category: String
    @NSManaged var dateAdded: NSDate
    @NSManaged var image: String
    @NSManaged var name: String
    @NSManaged var subCategory: String

    var groupByMonth: String{
    get{
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MMM yyyy"
        return dateFormatter.stringFromDate(self.dateAdded)
    }
}

var fetchedResultsController: NSFetchedResultsController = {
    let fetchRequest = NSFetchRequest(entityName: "Item")

    let sort = NSSortDescriptor(key: "dateAdded", ascending: false)
    fetchRequest.sortDescriptors = [sort]

    fetchRequest.fetchBatchSize = 20

    let result = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.appDelegate.childManagedObjectContext!, sectionNameKeyPath: groupByMonth, cacheName: nil)
    result.delegate = self

    return result
}()
© www.soinside.com 2019 - 2024. All rights reserved.