Reputation: 77
How can I use Sort in CoreData? I want to sort them by property, which is time
I also want to use these two threads. Someone knows how to use these two :
fetchOffset <==========
fetchLimit <===========
final class PersistantManager {
private init(){}
static let shared = PersistantManager()
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "_chans_")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
lazy var context = persistentContainer.viewContext
// MARK: - Core Data Saving support
func save () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
print("success save")
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func fetch<T: NSManagedObject>(_ objectType : T.Type) -> [T] {
let entityname = String(describing: objectType)
let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityname)
do {
let fetchedobject = try context.fetch(fetchrequest) as? [T]
return fetchedobject ?? [T]()
}catch{
print(error)
return [T]()
}
}
}
and my code for fetch :
guard let Bookmarks = try! PersistantManager.shared.context.fetch(HistoryBookmarks_Coredata.fetchRequest()) as? [HistoryBookmarks_Coredata] else {return}
Upvotes: 0
Views: 131
Reputation: 946
All you need to do is set the sort descriptors of the fetch request.
// replace "key" with the property you want to sort by
let sort = NSSortDescriptor(key: "key", ascending: false)
let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityname)
fetchrequest.sortDescriptors = [sort]
The fetchLimit specifies the maximum number of records to fetch.
The fetchOffset allows you to skip a specified number of rows.
If you want to know what a property is for, the documentation is a good place to start.
Upvotes: 1