84

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?

7 Answers 7

94

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.

2
  • 6
    A much more constructive answer - you should be marked as the solution!
    – Grouchal
    Jul 16, 2011 at 10:50
  • 1
    Generating UUID is best way to go. We are using it in our app and it is serving very well.
    – object2.0
    May 7, 2013 at 13:01
49

Keep in mind that Core Data is an object-graph persistence framework, not a database. Things like primary keys are abstracted away because they depend on the implementation of the persistent store.

2
  • 2
    This should've been the answer the answer @Mugunth should've chosen! Thank you for your insight.
    – Leonard
    Dec 4, 2013 at 0:28
  • so will Core Data just generate the primary key on its own? Aug 17, 2017 at 17:49
24

Core Data makes its own primary key - you don't have to add one. You can retrieve it with

NSManagedObjectID *moID = [managedObject objectID];
14

sometimes when hacking one needs the actual int of the primary key. here is how one can grab it:

NSManagedObjectID *yourManagedObjectID = [yourManagedObject objectID];
int yourManagedObject_PK = [[[[[yourManagedObjectID URIRepresentation] absoluteString] lastPathComponent] substringFromIndex:1] intValue];

despite CoreData being an object graph, if one looks at the CoreData generated SQLite database data, this way of grabbing the primary key of an NSManagedObject should not be a problem. ii have used CoreData and the low level sqlite3 C library together in the same code and passing primary keys from CoreData to sqlite3 for fetching records works just fine.

! if You intend to use this code in production, be aware of possible internal changes to the way the db primary key transforms into a URIRepresentation, it might brake Your code.

enjoy

10
  • 1
    No relation is defined between object-ID and SQLite RID. Could be usable for temporary key only for specific version, but wrong approach for persistent Primary Key because it can be broken at other version silently.
    – eonil
    Sep 18, 2012 at 4:08
  • what exactly did You mean by "broken at other version"? why should primary keys change?
    – manitu
    Sep 27, 2012 at 14:19
  • PK values won't be changed, but algorithm which makes URL representation may be changed, because no algorithm is defined officially. And in that case your code is not guaranteed to extract valid PK value. (if you have any source defines the algorithm, let me know, then I will recommend you posting)
    – eonil
    Sep 27, 2012 at 16:56
  • 1
    OK. sometimes when hacking part is convincible. My down-vote is currently locked-in, so you make some edit I will remove the down-vote.
    – eonil
    Sep 29, 2012 at 7:47
  • 2
    For sake of speed and effectiveness, sql is sometimes the way to go. My exemple, a query holding count(*), sums, averages and groups. Its a PAIN to do in OO, single line for sql! That 'hack' works perfectly and if Apple change it, well they will have to still make the sql join work in some way, so I guess we are ok for a while ;). Vote UP even if theoretically we shouldn't do this. Hiding completely the DB is, in my opinion, an error more driven by principles than real technical reasons. We do that, get batches by SQL. all the time in many other systems even though a framework is available. Sep 25, 2014 at 2:15
0

Without hacking NSManagedObjectID you can perform a fast check for your attribute before manage your remote data collection.

I've made an utility method, check it here

0

A Swift Extension to retrieve the primary key

extension NSManagedObject {
    var primaryKey : String {
        guard objectID.uriRepresentation().lastPathComponent.count > 1 else { return "" }
        return objectID.uriRepresentation().lastPathComponent.substring(from: 1)
    }
}

And for String

extension String
{
    func substring(from : Int) -> String {
        guard self.count > from else { return "" }
        return String(self[self.index(self.startIndex, offsetBy: from)...])
     }
}
-4

I'd rather use Time + the Class name as the unique identifier.

3
  • 2
    Not really recommended, when can you guarantee that not more than one object is created at the same time?
    – fat32
    Jan 10, 2016 at 10:08
  • Not recommended too . This method can't guarantee the key is unique.
    – Cody
    Jun 25, 2016 at 13:58
  • @Fynh I dint posted the code and ya my post may in incomplete though, I am always sync'ing the time getter method. Jun 26, 2016 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.