GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Day 58: App is creating an infinite list of users

Forums > 100 Days of SwiftUI

I'm currently working throuhg Day 58 and just completed the Relationships with SwiftData, SwiftUI, and @Query section. After adding the addSample() method, the user inside the method, "Piper Chapman", ends up being created an infinite number of times (or at least it appears that way) in the simulator. How do I resolve this?

Here's my Users view where Paul adds the user:

@Environment(\.modelContext) var modelContext
    @Query var users: [User]

    var body: some View {
            List(users) { user in
                HStack {
                    Text(user.name)

                    Spacer()

                    Text(String(user.jobs.count))
                        .fontWeight(.black)
                        .padding(.horizontal, 15)
                        .padding(.vertical, 5)
                        .background(.blue)
                        .foregroundStyle(.white)
                        .clipShape(.capsule)
                }
                .onAppear(perform: addSample)
            }
    }

    init(minimumJoinDate: Date, sortOrder: [SortDescriptor<User>]) {
            _users = Query(filter: #Predicate<User> { user in
                    user.joinDate >= minimumJoinDate
            }, sort: sortOrder)
    }

    func addSample() {
            let user1 = User(name: "Piper Chapman", city: "New York", joinDate: .now)
            let job1 = Job(name: "Organize sock drawer", priority: 3)
            let job2 = Job(name: "Make plans with Alex", priority: 4)

            modelContext.insert(user1)

            user1.jobs.append(job1)
            user1.jobs.append(job2)
    }
}

#Preview {
    Users(minimumJoinDate: .now, sortOrder: [SortDescriptor(\User.name)])
        .modelContainer(for: User.self)
}

   

Every time you launch the application in the simulator, this code runs:

//                  👇🏼 Create Piper Chapman each time you run the app.
.onAppear(perform: addSample)

If you are not checking for uniqueness, SwiftData will create (and save) a new version of this user every time you run the app in the simulator.

Delete the App in the Simulator

Just as you would on a physical iPhone, press and hold on the app's icon. Navigate through all the warnings and delete the app. This not only deletes the app, it also deletes SwiftData files and related supporting files.

Then launch the app again from Xcode.

Perhaps this time, you only see ONE Piper Chapman in your list?

Here's a debugging tip:

// Change this line and add a random number to Piper's name.
let user1 = User(name: "Piper Chapman", city: "New York", joinDate: .now)

// Like this                         👇🏼
let user1 = User(name: "Piper \(Int.random(in: 100...999)", city: "Bath", joinDate: .now)

How does that help you? Examine the code and tell us what you see when you run the app a few times in the simulator.

Keep Coding!

1      

After following the instructions in your response, I deleted the onAppear() modifier from my UsersView and instead placed the Piper user inside the ContentView like so:

let user1 = User(name: "Piper \(Int.random(in: 100...999))", city: "Bath", joinDate: .now)
                        let job1 = Job(name: "Organize sock drawer", priority: 3)
                        let job2 = Job(name: "Make plans with Alex", priority: 4)

                        modelContext.insert(user1)
                        user1.jobs?.append(job1)
                        user1.jobs?.append(job2)

I no longer have a lengthy list of one user!

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

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.