Search code examples
swiftcore-datansfetchedresultscontroller

Grouping core data with NSFetchedResultsController in swift


I'm displaying core data using NSFetchedResultsController. Below is my CoreData class

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

I want to display all items in groups. Items will be grouped based on the months of the dateAdded. That is, section header will display month and row will display the items added in that month.

Below is my code for 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
}()

How can I achieve this. Any help will be appreciated.

Thanks in advance


Solution

  • Easiest way is to add an attribute dateAddedMonth to store your NSDate only with the month. You can then set sectionNameKeyPath to "dateAddedMonth".