CoreData SQLite3 Database Constraint Failed Error

Have you ever seen the following error message:

Error Domain=NSCocoaErrorDomain Code=256 UserInfo=0x3baae90 "Operation could not be completed. (Cocoa error 256.)

Talk about not Helpful.

Inside this there was a userInfo dictionary with the following message:

error during SQL execution : constraint failed

Slightly more helpful, but not by very much.

We came across this error message while we were developing our Electrophobe game. We started the debugging process by inserting logging code and pinpointing where the code was failing out. After about 6 hours of work combing through both code and rebuilt databases we finally found the solution.

The trick was that the primary key store for the SQLite3 database that was backing our CoreData NSPersistenceStore had an incorrect value for the Z_MAX column. This column is used, we believe, to house the maximum primary key in order to quickly retrieve it for additional inserts.

As is evident from our escapade however, it is clearly a little vulnerable to tampering when loading the data directly into the SQLite database. To fix the issue, simply update the table with the max(Z_ID) from the referenced table and it should all hook up again.

404