{"id":261,"date":"2015-09-12T01:27:18","date_gmt":"2015-09-11T23:27:18","guid":{"rendered":"http:\/\/dorianroy.com\/blog\/?p=261"},"modified":"2015-09-12T01:31:25","modified_gmt":"2015-09-11T23:31:25","slug":"how-to-implement-unique-constraints-in-core-data-with-ios-9","status":"publish","type":"post","link":"https:\/\/dorianroy.com\/blog\/archives\/261","title":{"rendered":"How to implement Unique Constraints in Core Data with iOS 9"},"content":{"rendered":"<p>With iOS 9, Apple introduces Unique Constraints for Core Data. This new feature was briefly demonstrated at WWDC in June (<a href=\"https:\/\/developer.apple.com\/videos\/wwdc\/2015\/?id=220\" target=\"_blank\">Session 220<\/a>). When I tried to implement it, I came across a few pitfalls and unexpected behavior, so I thought this might be worth a blog post.<\/p>\n<p>Unique Constraints are a way to declare a custom attribute to be unique across all instances of an entity. Its intended use case is the import of external data that should be merged with existing objects in the database.<br \/>\n<!--more--><\/p>\n<h3>No more fetch\/if\/else<\/h3>\n<p>Until now, when you wanted to import data objects into Core Data from a file or network request, you had to create a fetch request for each incoming object with a predicate that matches the id and then execute it to look for an existing version of that object. If you found one, you would update it, otherwise create a new object. With Unique Constraints, you don\u2019t have to do this fetch\/if\/else anymore and save lots of DB requests while parsing the data.<br \/>\n<figure id=\"attachment_267\" aria-describedby=\"caption-attachment-267\" style=\"width: 701px\" class=\"wp-caption alignnone\"><a href=\"http:\/\/dorianroy.com\/blog\/wp-content\/uploads\/2015\/09\/Screen-Shot-2015-08-27-at-18.05.23.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/dorianroy.com\/blog\/wp-content\/uploads\/2015\/09\/Screen-Shot-2015-08-27-at-18.05.23.png\" alt=\"Core Data Unique Constraints Dialog in Xcode 7.0\" width=\"701\" height=\"296\" class=\"size-full wp-image-267\" srcset=\"https:\/\/dorianroy.com\/blog\/wp-content\/uploads\/2015\/09\/Screen-Shot-2015-08-27-at-18.05.23.png 701w, https:\/\/dorianroy.com\/blog\/wp-content\/uploads\/2015\/09\/Screen-Shot-2015-08-27-at-18.05.23-300x127.png 300w\" sizes=\"auto, (max-width: 701px) 100vw, 701px\" \/><\/a><figcaption id=\"caption-attachment-267\" class=\"wp-caption-text\">Unique Constraints Dialog for Core Data Entities in Xcode 7.0 (bottom right)<\/figcaption><\/figure> Instead, you list the name of the id attribute(s) that you use in the new Constraints box of the Entity Property Inspector in the Data Model View in Xcode 7. In your code you then just create a new object with <span class=\"lang:swift decode:true  crayon-inline \" >NSEntityDescription.insertNewObjectForEntityForName(_:inManagedObjectContext:)<\/span>, set the value for the unique attribute (and all other attributes you\u2019re importing) and finally save the context. Core Data will automatically check if there is an existing object with the same unique attribute and &#8230; throw an error if it finds one. At least that\u2019s the default behavior, which caused <a href=\"https:\/\/twitter.com\/Ehrippura\/status\/630274558923251712\" target=\"_blank\">some<\/a> <a href=\"http:\/\/stackoverflow.com\/a\/31339077\/986462\" target=\"_blank\">confusion<\/a>.<\/p>\n<h3>Unique Constraints conflicts are like merge conflicts&#8230;<\/h3>\n<p>Core Data handles the new kind of conflict caused by multiple instances with the same <em>custom<\/em> unique attribute in the same way as conflicts between different versions of an object with the same <em>internal<\/em> <span class=\"lang:swift decode:true  crayon-inline \" >objectID<\/span> (which can happen when you use the same persistent store with different contexts). That makes perfect sense but was a little surprising to me at first, because I never used to get this kind of conflict with newly created objects (they can&#8217;t have a newer version with the same <span class=\"lang:swift decode:true  crayon-inline \" >objectID<\/span> in the persistent store).<\/p>\n<p>It doesn\u2019t matter if the conflict exists between two newly created objects in the same context or between a new object and an existing object in the database. Core Data handles all conflicts according to the setting for the <span class=\"lang:swift decode:true  crayon-inline \" >mergePolicy<\/span> of the context that you\u2019re trying to save. The default value <span class=\"lang:swift decode:true  crayon-inline \" >NSErrorMergePolicy<\/span> throws an error that includes a list of conflicting objects, so you could resolve the conflicts yourself (which wouldn\u2019t be much of an improvement over the old fetch\/if\/else). <\/p>\n<p>What you probably want to use instead is <span class=\"lang:swift decode:true  crayon-inline \" >NSMergeByPropertyObjectTrumpMergePolicy<\/span>, which overwrites every property of the old object that has changed in the new one. At least that\u2019s how the latter works for conflicts between existing objects.<\/p>\n<h3>&#8230; but different<\/h3>\n<p>With Unique Constraints, <span class=\"lang:swift decode:true  crayon-inline \" >NSMergeByPropertyObjectTrumpMergePolicy<\/span> overwrites <em>all<\/em> attributes, just not the relationships. I guess that is inevitable as even an optional attribute on the new object that has not been set (i.e equals nil), is still \u201cnew\u201d information compared to the existing object. Core Data cannot know if you haven\u2019t set it because you want to keep the old value or if you want it to be nil on purpose in order to remove it.<\/p>\n<p>So, if you just want to augment existing objects with new data, you\u2019ll have to resort to solving the conflicts yourself (you could also create your own subclass of <span class=\"lang:swift decode:true  crayon-inline \" >NSMergePolicy<\/span> to do so). <\/p>\n<p>A more elegant way in such a case (and probably also a better overall design) is to split your object into separate entities that are connected with a relationship. Take for example a shopping app where the user can tag the products. When you update the product price by importing external data, you don\u2019t want to lose the user tags. Instead of writing the tags into a string-attribute of your Product entity, you could create a Tag entity, attached to the product with a to-many relationship. Now when you insert a new Product with the updated price and save using <span class=\"lang:swift decode:true  crayon-inline \" >NSMergeByPropertyObjectTrumpMergePolicy<\/span>, Core Data will overwrite the price (together with all other attributes) but keep the relationship to the user-defined tags.<\/p>\n<p>A few other things I came across:<\/p>\n<li>Unique Constraints must be strings<\/li>\n<li>When you try to save a context with more than one object with the same value for a Unique Constraint, the first one you created is the one that gets saved<\/li>\n<li>If you have parent\/child contexts, you need to set the merge policy on each one of them<\/li>\n<li>The &#8220;Tools Version&#8221; of your data model file must be set to &#8220;Xcode 7.0\u201d<\/li>\n<li>Unique Constraints is iOS 9.0 only, so you need to set your deployment target to iOS 9.0 as well<\/li>\n","protected":false},"excerpt":{"rendered":"<p>With iOS 9, Apple introduces Unique Constraints for Core Data. This new feature was briefly demonstrated at WWDC in June (Session 220). When I tried to implement it, I came across a few pitfalls and unexpected behavior, so I thought this might be worth a blog post. Unique Constraints are a way to declare a &hellip; <a href=\"https:\/\/dorianroy.com\/blog\/archives\/261\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">How to implement Unique Constraints in Core Data with iOS 9<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38,39,40],"tags":[],"class_list":["post-261","post","type-post","status-publish","format-standard","hentry","category-core-data","category-ios","category-ios-9-0"],"_links":{"self":[{"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/posts\/261","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/comments?post=261"}],"version-history":[{"count":34,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/posts\/261\/revisions"}],"predecessor-version":[{"id":302,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/posts\/261\/revisions\/302"}],"wp:attachment":[{"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/media?parent=261"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/categories?post=261"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dorianroy.com\/blog\/wp-json\/wp\/v2\/tags?post=261"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}