在 CoreData 中排序 (swift)

Sort in CoreData (swift)

如何在 CoreData 中使用排序? 我想按属性排序,也就是时间

我也想用这两个线程。有人知道如何使用这两个:

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]()
    }

}

}

和我的获取代码:

guard let Bookmarks = try! PersistantManager.shared.context.fetch(HistoryBookmarks_Coredata.fetchRequest()) as? [HistoryBookmarks_Coredata] else {return}

您需要做的就是设置获取请求的排序描述符。

// 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]

fetchLimit 指定要提取的最大记录数。

fetchOffset 允许您跳过指定行数。

如果您想知道 属性 的用途,文档是一个很好的起点。