Reputation: 2248
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
Upvotes: 3
Views: 2220
Reputation: 2248
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
}()
Upvotes: 9
Reputation: 1466
Easiest way is to add an attribute dateAddedMonth
to store your NSDate
only with the month. You can then set sectionNameKeyPath
to "dateAddedMonth"
.
Upvotes: 2