How to Implement Unique Constraints in Core Data
Posted By : Varun Wadhwa | 29-Apr-2016
Unique constraints is a way to declare an attribute to be unique across all objects of an entity and it is introduced with IOS 9.
To make an attribute unique goto data model editor and select the attribute , click + button and then type the attribute name.
suppose you have already inserted some data in core data, now if you try to insert a same value multiple time for attribute “id” , and try to save it in core data it’ll throw an exception(by default) and result will be not saved .
in our case id = 1 have exist so its throwing an exception. this is because the default merge policy of managed object context is NSErrorMergePolicy.
so we need to set Merge policy of managed object context to NSMergeByPropertyObjectTrumpMergePolicy (which overwrites the data)
func saveData() {
let managedObjectContex = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
managedObjectContex.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
do {
try managedObjectContex.save()
}
catch let error as NSError {
NSLog("\(error)")
}
}
now if you try to save the data the output will be :
as you can see the value for name has overwritten.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Varun Wadhwa
Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.