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:
I need the "id" attribute is my primary key.
May be the same in Objective-C, just need to know how to define it.
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(...)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With