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
- I created a Model version
- Unchecked optional for
uniqueIdentifierattribute (To make it non-optional) - Added uniqueIdentifier to
constraintssection ofNameEntityentity - (To set it as unique attribute) - 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?