Search code examples
ioscore-dataunique

Manage Compound Primary Key in Core Data


I want to create compound unique key in core-data, as actual primary key in core-data is ObjectId. Please let me know, how could we achieve the same.

Updated Question:

I am having an entity which is working as a template. And that template is being getting created on server with particular combinations.

Like Entity Name : E
and there are 4 attributes A, B, C, D.

Now the entity is unique with following combination

A1-B1-C1-D1
A1-B2-C1-D1
....

So actually it is permutation combination of multiple attributes to create a uniqueness.

Now I want to detect these uniqueness during updating the records.


Solution

  • ObjectID is NOT the primary key. There is no primary key in Core Data.

    Core Data is NOT a database. Treating it like a database in your designs will cause issues. Core Data is an object graph that can persist to disk and one of the formats that it can persist to is a database. Treat it like an object graph first and foremost.

    The ability to have a unique ID for duplicate detection was added in iOS 9 and OS X 10.11. Review the WWDC video from 2015 to understand those changes.

    Update

    Even after your update my answer is still accurate. In iOS 9 they added the ability to define a unique id across properties that will aid in the update/insert problem. Watch the 2015 WWDC video for details on this feature.

    If you are aiming for something older than iOS 9 then, no; there is no feature in Core Data that solves this issue for you and you will need to solve it yourself. This is a part of the classic "insert vs. update" problem that all persistence layers face.

    The solution is to create a list of IDs and then fetch all objects that have those identifiers then iterate over what you are processing and use the fetched list to determine if you are going to need to insert or not.

    Updating to iOS 9 and using the new API is easier.