I’m new to iOS development and currently learning to persist data using SwiftData. I’m building a very simple to-do list app to understand how local persistence works.
However, I’ve hit a wall and when I call context.insert(item), the new task never appears in my list, and my @Query array (items) always has a count of 0. I’ve reviewed documentation, watched tutorials, and even asked ChatGPT, but I still can’t figure out what’s missing.
Here’s my setup:
import Foundation
import SwiftData
@Model
class DataItem: Identifiable {
var id: UUID = UUID()
var text: String
var isCompleted: Bool = false
init(text: String) {
self.text = text
}
}
import SwiftUI
@main
struct SwiftDataIssueApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: DataItem.self)
}
}
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var context
@Query private var items: [DataItem]
@State private var newTask: String = ""
var body: some View {
NavigationView {
List {
ForEach(items) { item in
Text(item.text)
}
}
.navigationTitle(Text("Tasks"))
VStack {
TextField("Enter New Task", text: $newTask)
Button("Add Task", action: addTask)
}
.padding()
}
}
func addTask() {
let item = DataItem(text: newTask)
context.insert(item)
print(item.text)
print(items.count)
newTask = ""
}
}
I do want to note that items.count keeps returning 0.
Does anyone know why?
items.countdoes not update immediately so that is expected, but the task not appearing in the list? I cannot reproduce that. Do you mean the task is not saved on the next launch? That is likely because you killed the app from Xcode and it hasn't had a chance to autosave.ContentViewthen the.modelContainer(for: DataItem.self)you put in theWindowGroupwill not do anything. Put.modelContainer(for: DataItem.self, inMemory: true)in your preview instead.