Cocoa Core Data efficient way to count entities

后端 未结 9 1768
滥情空心
滥情空心 2020-11-30 16:45

I read much about Core Data.. but what is an efficient way to make a count over an Entity-Type (like SQL can do with SELECT count(1) ...). Now I just solved this task with s

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 17:40

    It's really just this:

    let kBoat = try? yourContainer.viewContext.count(for: NSFetchRequest(entityName: "Boat"))
    

    "Boat" is just the name of the entity from your data model screen:

    What is the global yourContainer?

    To use core data, at some point in your app, one time only, you simply go

    var yourContainer = NSPersistentContainer(name: "stuff")
    

    where "stuff" is simply the name of the data model file.

    You'd simply have a singleton for this,

    import CoreData
    public let core = Core.shared
    public final class Core {
        static let shared = Core()
        var container: NSPersistentContainer!
        private init() {
            container = NSPersistentContainer(name: "stuff")
            container.loadPersistentStores { storeDescription, error in
                if let error = error { print("Error loading... \(error)") }
            }
        }
        
        func saveContext() {
            if container.viewContext.hasChanges {
                do { try container.viewContext.save()
                } catch { print("Error saving... \(error)") }
            }
        }
    }
    

    So from anywhere in the app

    core.container
    

    is your container,

    So in practice to get the count of any entity, it's just

    let k = try? core.container.viewContext.count(for: NSFetchRequest(entityName: "Boat"))
    

提交回复
热议问题