2024-12-18
如果要实现数据库的实时更新,必须要context.save()。
关键是modelContainer的配置和print路径配置。
import SwiftUI
@main
struct Todoey_swiftDataApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: Item.self)
    }
    
    init(){
        print(URL.applicationSupportDirectory.path(percentEncoded: false))
    }
}
Item.self是一个表的名字,如果需要增加表,则modelContainer要改成数组形式,如modelContainer(for: [Item.self, Category.self])。
根据print(URL.applicationSupportDirectory.path(percentEncoded: false)),运行程序后会打印出数据库的路径,然后用DB Browser for SQLite打开这个路径下的数据库文件,就可以看到数据了。
context.insert()
@Environment(\.modelContext) private var context
Button("添加") {
                    let newItem = Item(title: title, done: done)
                    context.insert(newItem)
                    do {
                        try context.save()  // 保存上下文的所有更改
                        isPresented = false
                    } catch {
                        print("保存数据时出错: \(error)")
                    }
重点是@Model
import SwiftData
@Model
class Item{
    var title: String
    var done: Bool
    
        init(
            title: String,
            done: Bool
        ){
            self.title = title
            self.done = done
        }
}
import SwiftData
@Environment(\.modelContext) private var context
@Query(sort: \Item.title) private var items: [Item]
List{
	ForEach(items){ item in
		Text(item.title)
	}
}
用getter和setter辅助修改
ForEach(items) { item in
                        Toggle(item.title, isOn: Binding(
                            //获取当前.done的值
                            get: { item.done },
                            //.done的值变化时,操作数据库
                            set: { newValue in
                                item.done = newValue
                                do {
                                    try context.save()
                                } catch {
                                    print("保存数据时出错: \(error)")
                                }
                                
                            }
                        ))
context.delete()
                        .swipeActions(edge: .trailing, allowsFullSwipe: true) {
                            Button(role: .destructive) {
                                context.delete(item)
                                do {
                                    try context.save()  // 提交更改
                                } catch {
                                    print("删除项目时出错: \(error)")
                                }
                            } label: {
                                Label("删除", systemImage: "trash")
                            }
                        }
swiftData教程-Paul Hudson-HackingWithSwift
以上的教程还有CoreData版本
更多教程,可以参考100天SwiftUI