3
votes

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

2
Apple provides sample code, "Custom Section Titles with NSFetchedResultsController" which should give you a starting point. - quellish

2 Answers

9
votes

I solved it as

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

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