Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a count of records in a core data entity

Does anyone know of an existing function or property that provides a count of the records in a Core Data entity?

like image 407
Spanky Avatar asked Jul 06 '10 06:07

Spanky


People also ask

What is Nsmanagedobjectcontext in core data?

An object space to manipulate and track changes to managed objects.

How can you retrieve data from core data?

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.

What is entity in 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.

What is entity in CoreData Swift?

An entity describes an object, including its name, attributes, and relationships. Create an entity for each of your app's objects.


2 Answers

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.

like image 60
mbauman Avatar answered Oct 02 '22 20:10

mbauman


   func getRecordsCount() {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: _entityName)
        do {
            let count = try context.count(for: fetchRequest)
            print(count)
        } catch {
            print(error.localizedDescription)
        }
    }
like image 32
Bibin Jaimon Avatar answered Oct 02 '22 20:10

Bibin Jaimon