Case insensitive Entity constraints in Core Data

How to make Entity unique constraints in Core Data case insensitive? I have an Entity that is keep unique by "name" property.

I've added target property in constraints, set context.mergePolicy = NSMergePolicy.rollback . Works correct here, skip entities with the same name.

But I want to skip aPpleS when I already have Apples. How to achieve that using merge policy? Does any Core Data solution where I can get case insensitive behavior?


Accepted Reply

You could just add a 'name_lowercased' attribute to your data model and make this your unique constraint instead. You can fill your object property with your 'name' and a .lowercased() call then.


After all the name "aPpleS" is different from "Apples".


If you really don't want that, there also is the option to implement your own MergePolicy, but that seems to be too much for your case.

Replies

I recommend using derived attributes. I haven't tried using them for unique constraints, but you can definitely use them to make an attribute that is an all-lowercase version of "name".

Derived attributes can't be used for unique constraints.

You will get the following error:

Failed to parse model XML with failure reason Property type is not valid for unique constraints.

You could just add a 'name_lowercased' attribute to your data model and make this your unique constraint instead. You can fill your object property with your 'name' and a .lowercased() call then.


After all the name "aPpleS" is different from "Apples".


If you really don't want that, there also is the option to implement your own MergePolicy, but that seems to be too much for your case.

Do you need to preserve cases? If not, you could just normalize them during validation.

Creating custom merge policy is an interesting idea. I will try to find any info about that, did not know it's possible.

Creating another property can work too.


Thanks!

You are welcome. It would be nice to chose an accepted answer to mark your original question as answered.