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

 

Related Tags

About Author

Author Image
Varun Wadhwa

Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.

Request for Proposal

Name is required

Comment is required

Sending message..