Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data Primary Key

This may seem stupid, but I still couldn't figure out how to mark a attribute as a primary key in the xcdatamodel file. My persistent storage is sqlite file. Can anyone help me?

In that case, how can I "validate" a ID to be unique? Should I write a validation method or something?

like image 996
Mugunth Avatar asked May 23 '09 14:05

Mugunth


People also ask

Can we set primary key in Core Data?

The answer is NO. To achieve similar thing, You can have an 'id' field in the table, before inserting into the table get the maximum value of the 'id' and then add 1 to the value. With a filed 'userID' in the table ENTITY_USER (users), the get the highest user ID.

What do you mean by Core Data?

Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores.

What type of database is Core Data?

Core Data is not a database. Core Data is a framework for managing an object graph. An object graph is nothing more than a collection of interconnected objects. The framework excels at managing complex object graphs.

Can you store an array in Core Data?

There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.


1 Answers

Your options are:

  • Use -[NSManagedObject objectID]. Note that this ID is temporary until either the object is saved for the first time or you call -[NSManagedObjectContext obtainPermanentIDsForObjects:error:]
  • Use the CFUUID family of functions to generate a UUID for each object in your -awakeFromInsert method
  • Create your own primary key-like system that stores an integer in your model and increments it with the creation of each object

There is no good way to validate that a property is unique. The closest you'll get is to ensure it is unique at creation time, and then implement a custom setter method that stops anyone ever changing the ID.

like image 79
Mike Abdullah Avatar answered Oct 07 '22 14:10

Mike Abdullah