Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data primary key ID for a row in the database

Suppose I have a list of books stored in Core Data. I want to search for a book by it's primary key ID.

I know the sqlite file created by Core Data has an ID column in each table, but this doesn't seem to be exposed to me in anyway.

Does anyone have any recommendations?

like image 804
WoodenKitty Avatar asked Jan 18 '11 03:01

WoodenKitty


People also ask

Can we set primary key in core data?

There is no concept of primary keys or foreign keys in CoreData.

What is an Nsmanagedobjectid?

A compact, universal identifier for a managed object.

What is a core database?

The Core database: Stores the configuration and settings for the Sitecore user interface, as well as store information such as users' preferences, event queues, and more. Developers may extend or customize items in the Core database - for example, as part of creating or modifying an interface.


1 Answers

-[NSManagedObject objectID] is the unique ID for an object instance in Core Data. It can be serialized via -[NSManagedObjectID URIRepresentation]. You can retrieve the objectID from a persistent store coordinator with -[NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] and then get the object from a managed object context with -[NSManagedObjectContext objectWithID:].

BUT

You should keep in mind that Core Data is not an ORM. It is an object graph management framework. That is uses SQLite (and unique row IDs) as a backend is purely an implementation detail. The sooner you can get yourself out of the SQL/RDBMS mindset, the faster you will be happy with Core Data. Instead of trying to find an object from a stored ID, consider why you need that object and what object needs it. If an instance of class Foo needs to be able to get to an instance of class Bar, why not just create an association from the Foo to the Bar and set the appropriate Bar instance as the target of the association on the appropriate Foo instance. Let Core Data keep track of object IDs.

like image 135
Barry Wark Avatar answered Oct 31 '22 06:10

Barry Wark