我正在使用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
}()
如何才能实现这个目标。任何帮助将被感激。
先谢谢你
最简单的方法是添加一个属性 dateAddedMonth
储存你的 NSDate
只与月份有关。然后您可以设置 sectionNameKeyPath
到 "dateAddedMonth"
.
我解决了它,因为
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
}()