Search code examples
ioscore-dataauto-incrementuniqueidentifier

Store and retrieve unique identifier from Core Data


iOS newb building an app to work with a website. Ultimately, I want to keep the app and backend on the website in sync.

Photos are saved on the website using the ID of the item. For the app, I would also like to save the photo with a unique number linked to the item.

On the website, the id of each item is simply the auto incremented number in a MYSQL table.

My understanding is autoincrementation is impossible in Core Data but it does create unique identifiers for each managed object.

How would I get and store this number in the core data database at the time the item is created for later retrieval?

Alternatively has anyone discovered a way to auto-increment in core data so as to give items numbers that could be used for storing photos. It would be nice to have a similar naming scheme for photos created by the app and those created through the website.


Solution

  • There is no 'built in' solution for creating an auto-incrementing id in Core Data. One important thing you should recognize is that Core Data is an object graph not a relational database. This is very important in understanding how you should approach design with Core Data.

    Yes, Core Data does create unique identifiers for objects in the form of GUIDs - so it's not a number, but rather 32 hexadecimal digits (Globally unigue identifier).

    You can write a method that will get the next number in a sequence for an entity, but Core Data will not do it for you.

    You may find the information in this question useful: Set auto increment in Core data iOS. I would not attempt to use NSManagedObjectID. This value can change.

    My suggestion is that you allow the MySQL database to assign the id's and simply store that id in a number property in the Core Data object. For items originating in the app leave the id property blank until it has been sent to the MySQL database for persistence. Then, retrieve the Id that the database assigned it and set it to the Core Data object's property.