Does anyone know of an existing function or property that provides a count of the records in a Core Data entity?
An object space to manipulate and track changes to managed objects.
Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.
An entity description describes an entity (which you can think of as a table in a database) in terms of its name, the name of the class used to represent the entity in your application, and what properties (attributes and relationships) it has.
An entity describes an object, including its name, attributes, and relationships. Create an entity for each of your app's objects.
I believe the best way to accomplish this is through NSManagedObjectContext's countForFetchRequest:error:
It works just like a regular fetch request, except that it only returns the count and presumably could therefore be more optimized.
func getRecordsCount() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: _entityName)
do {
let count = try context.count(for: fetchRequest)
print(count)
} catch {
print(error.localizedDescription)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With