CoreData Migration: Make an attribute both non-optional & unique

Viewed 49

I have an entity called NameEntity, it has optional attribute uniqueIdentifier. Now I want to make this attribute non-optional as well as unique to avoid duplicate entries.

What I did

  1. I created a Model version
  2. Unchecked optional for uniqueIdentifier attribute (To make it non-optional)
  3. Added uniqueIdentifier to constraints section of NameEntity entity - (To set it as unique attribute)
  4. Created a MappingModel for v1 to v2 where I added Migration policy that deletes the duplicate entries in that entity.

With all these changes, as soon as I run the app, app crashes by showing the below error,

Cannot migrate store in-place: constraint violation during attempted migration
NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134111 "(null)" 
UserInfo={_NSCoreDataOptimisticLockingFailureConflictsKey=(), 
NSUnderlyingException=Constraint unique violation: UNIQUE constraint failed: ZNAMEENTITY.ZUNIQUEIDENTIFIER, 
reason=constraint violation during attempted migration, 
NSExceptionOmitCallstacks=true}

But, If I set/keep the Optional checkbox of uniqueIdentifier, app doesn't crash and goes through the migration process. This avoids duplicate entries BUT still allows the nil values.

So, How can I make an optional attribute both non-optional & unique in the CoreData migration?

0 Answers
Related