TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Ensuring Core Data objects are unique using constraints

Paul Hudson    @twostraws   

By default Core Data will add any object you want, but this can get messy very quickly, particularly if you know two or more objects don’t make sense at the same time. For example, if you stored details of contacts using their email address, it wouldn’t make sense to have two or three different contacts attached to the same email address.

To help resolve this, Core Data gives us constraints: we can make one attribute constrained so that it must always be unique. We can then go ahead and make as many objects as we want, unique or otherwise, but as soon as we ask Core Data to save those objects it will resolve duplicates so that only one piece of data gets written. Even better, if there was some data already written that clashes with our constraint, we can choose how it should handle merging the data.

To try this out, create a new entity called Wizard, with one string attribute called “name”. Now select the Wizard entity, look in the data model inspector for Constraints, and press the + button directly below. You should see “comma,separated,properties” appear, giving us an example to work from. Select that and press enter to rename it, and give it the text “name” instead – that makes our name attribute unique. Remember to press Cmd+S to save your change!

Now go over to ContentView.swift and give it this code:

struct ContentView: View {
    @Environment(\.managedObjectContext) var moc

    @FetchRequest(sortDescriptors: []) var wizards: FetchedResults<Wizard>

    var body: some View {
        VStack {
            List(wizards, id: \.self) { wizard in
                Text( ?? "Unknown")

            Button("Add") {
                let wizard = Wizard(context: moc)
       = "Harry Potter"

            Button("Save") {
                do {
                } catch {

You can see that has a list for showing wizards, one button for adding wizards, and a second button for saving. When you run the app you’ll find that you can press Add multiple times to see “Harry Potter” slide into the table, but when you press “Save” we get an error instead – Core Data has detected the collision and is refusing to save the changes.

If you want Core Data to write the changes, you need to open DataController.swift and adjust the loadPersistentStores() completion handler to specify how data should be merged in this situation:

container.loadPersistentStores { description, error in
    if let error = error {
        print("Core Data failed to load: \(error.localizedDescription)")

    self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump

That asks Core Data to merge duplicate objects based on their properties – it tries to intelligently overwrite the version in its database using properties from the new version. If you run the code again you’ll see something quite brilliant: you can press Add as many times as you want, but when you press Save it will all collapse down into a single row because Core Data strips out the duplicates.

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.