Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Core Data set attribute primary key

I am developing an application in Swift and started using Core Data recently. I must define which attribute to my entity will be my primary key. For example:

I have an entity that has the attributes of the class:

  • id
  • name
  • age

I need the "id" attribute is my primary key.

May be the same in Objective-C, just need to know how to define it.

like image 779
Gian Avatar asked Nov 07 '14 10:11

Gian


2 Answers

Each NSManagedObject has its own unique key built in which is available in its objectID property.

This id is internally used to link entities over its relations. There is no need to maintain an own id as a primary key as you are used to do in SQL.

You can always get the id by NSManagedObject.objectID.

Fetching an object by its id can be performed directly by the managed object context using NSMananagedObjectContext.objectWithId(...)

like image 65
zisoft Avatar answered Oct 08 '22 01:10

zisoft


Why do you need id to be your primary key, it's not SQL and there is not primary key (even if behind core data it's SQL you don't use SQL and primary key). Rename your attribute id in userId, or entityId. When you want to get your entity with your id use a NSPredicate:

 [NSPredicate predicateWithFormat:@"(entityId == %d)", entityId]
like image 21
Jonathan Vukovich-Tribouharet Avatar answered Oct 08 '22 02:10

Jonathan Vukovich-Tribouharet