Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of existing entities(tables) in core data

Tags:

ios

core-data

How to get list of existing entities (tables) for a particular schema (Managed Object Model) in core data. I just started implementing core data concept and stuck with these points.

Something like:

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Thanks

like image 268
Anil Kumar Avatar asked Mar 27 '13 05:03

Anil Kumar


2 Answers

You should read through Apple's Core Data Programming Guide. To get the entities for a particular NSManagedObjectModel, you would use one of the following (this assumes you have an NSManagedObjectModel named objectModel):

NSArray *myEntities = [objectModel entities];
// Array of all entities in the model

or

NSDictionary *myEntities = [objectModel entitiesByName];
// Dictionary of entities in the model, with the entity names as keys

You can read more in the NSManagedObjectModel Class Reference.

It appears you're coming from a SQL background (as I was). There are a number of concepts in Core Data that are different - sometimes for the better, once you understand them, sometimes requiring more work than a simple SQL statement you may be used to. I think it's important to approach Core Data without SQL "baggage" and treat it as if you're learning how to use a database for the first time - this will help avoid frustration.

like image 87
David Ravetti Avatar answered Nov 12 '22 15:11

David Ravetti


In Swift it would be:

let model: NSManagedObjectModel

let entities: [NSEntityDescription] = model.entities
// or
let entitiesByName: [String: NSEntityDescription] = model.entitiesByName

and to get a list of names

let enititesNames: [String] = entities.compactMap(\.name)
like image 24
Witek Bobrowski Avatar answered Nov 12 '22 17:11

Witek Bobrowski