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

SwiftData @Attribute(.unique) not working

Forums > iOS

I'm trying to implement something similar to this tutorial, but my app keeps getting duplicate values in the database and/or crashing. I've distilled my problem down to the following minimal ContentView.swift:

import SwiftUI
import SwiftData

@Model
final class User {
    @Attribute(.unique) var id: Int
    var email: String

    init(id: Int, email: String) {
        self.id = id
        self.email = email
    }
}

struct ContentView: View {
    @Environment(\.modelContext) var modelContext
    @Query var users: [User]

    var body: some View {
        List(users) { user in
            Text("\(user.id): \(user.email)")
        }
        .onAppear {
            let user = User(id: 1, email: "blah@example.com")
            modelContext.insert(user)
        }
    }
}

just add .modelContainer(for: User.self) to your WindowGroup. The behavior only seems to be happening when I run the app on device, force quit it and reopen. This causes the user to be duplicated in the list, and then the app to crash.

Is there something wrong with the code? Is this some kind of bug? What's going on here?

3      

In my case your code works just fine. But beware you if had you DB with id property NOT indicated as unique at the outset, and then if you changed it to be unique you app will crash. For that you need to either delete your app from device and run it again, or mark your property as optional for lightweight migration to work.

Otherwise I copied your code, run on simulator, forced quit it and rerun again, it works...

3      

For me it was only happening when I ran it on the iPhone itself, not in the simulator.

3      

If anyone else is encountering this problem, I found that writing this worked:

DispatchQueue.main.async {
       modelContext.insert(user)
       try? modelContext.save()
}

4      

I too had this same issue, and solved it very similarly. Thanks for the pointer! It was driving me absolutely nuts that it would work fine in the simulator but fail on-device.

            DispatchQueue.main.async {
                apiRes.forEach {
                    modelContext.insert(Flight(data: $0))
                }
                try? modelContext.save()
            }

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.