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.
For Update No more fetch/if/else Needed When adding the Constraints
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 executes 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’t have to do this fetch/if/else anymore and save lots of DB requests while parsing the data.
Follow Below Steps For Add The Constraints
Step 1-> Create the Entity
First, we will create an Entity with the data model.
Step 2-> Add The Constraints For Notes Entity
Here we have added the “title” with Notes Entity as Constraints.
Step 3-> Add The Merge Policy For for Context
1 2 3 4 5 |
var context: NSManagedObjectContext = { let x = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext x.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return x }() |
Here we add the NSMergeByPropertyObjectTrumpMergePolicy for make the record unique.
Step 4-> Add The Below Code For Save The Notes Entity Object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
func saveData(_ title: String, _ description: String, _ time: String) -> Bool { let userEntity = NSEntityDescription.entity(forEntityName: "Notes", in: context)! let user = NSManagedObject(entity: userEntity, insertInto: context) user.setValue(title, forKeyPath: "title") user.setValue(description, forKey: "descript") user.setValue(time, forKey: "time") do { try context.save() } catch let error as NSError { print("Could not save. \(error.localizedDescription)") return false } return true } |
Step 5-> Update The First Row With Same Title And Different Description. Which Will Work As Primary Key Concept.
with the help of constraint, we will make each object unique.
Conclusion
So pls follow the above step and And if you have any issue or suggestion you can leave your message in the comment section I will try to solve this.