使用swift中的NSFetchedResultsController对核心数据进行分组

时间:2015-09-25 06:48:27

标签: swift core-data nsfetchedresultscontroller

我使用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
}()

我怎样才能做到这一点。任何帮助将不胜感激。

提前致谢

2 个答案:

答案 0 :(得分:7)

我解决了它

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
}()

答案 1 :(得分:2)

最简单的方法是添加属性dateAddedMonth,以便仅在月份中存储NSDate。然后,您可以将sectionNameKeyPath设置为"dateAddedMonth"