模型上下文

温馨提示:本文最后更新于2025-01-18 12:33:10,某些文章具有时效性,若有错误或已失效,请在下方留言

ModelContext 是 SwiftData 中负责跟踪所有在内存中创建、修改和删除的对象的组件。它确保这些对象能够在稍后某个时刻保存到模型容器中。ModelContext 提供了一个便捷的方式来管理对象的状态,使开发者能够轻松执行 CRUD(创建、读取、更新、删除)操作而不必担心对象的持久化细节。通常,ModelContextModelContainerModelConfiguration 配合使用,共同实现数据的高效管理和操作。

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var context
}

插入新模型

这个示例展示了如何在 SwiftUI 中插入一个新模型到 ModelContext

import SwiftData

@Model final class Recipe {
    var id: UUID
    var name: String
    var destination: String
    init(id: UUID = UUID(), name: String = "", destination: String = "") {
        self.name = name
        self.destination = destination
    }
}

struct AddRecipeView: View {
    @Environment(\.modelContext) private var context
    @State private var recipeName: String = ""
    var body: some View {
        VStack {
            TextField("Recipe Name", text: $recipeName)
            Button("Add Recipe") {
                let newRecipe = Recipe(name: recipeName)
                context.insert(newRecipe) // 插入新模型
                recipeName = "" // 清空输入框
            }
        }
    }
}

更新模型

在这个示例中,您可以更新现有模型的名称。更新后,如果自动保存未被启用,可以选择手动保存。

import SwiftData

struct RecipeListView: View {
    @Environment(\.modelContext) private var context
    @Query private var recipes: [Recipe]
    var body: some View {
        List(recipes) { recipe in
            HStack {
                Text(recipe.name)
                Spacer()
                Button("Edit") {
                    // 更新模型
                    if let index = recipes.firstIndex(where: { $0.id == recipe.id }) {
                        recipes[index].name = "Updated Recipe Name"
                        // 如果禁用了自动保存,这里需要手动保存
                        // try? context.save() // 手动保存更改
                    }
                }
            }
        }
    }
}

删除模型

这个示例展示了如何从 ModelContext 中删除一个模型。删除操作将使该模型从持久化存储中移除。

import SwiftData

struct RecipeListView: View {
    @Environment(\.modelContext) private var context
    @Query private var recipes: [Recipe]

    var body: some View {
        List(recipes) { recipe in
            HStack {
                Text(recipe.name)
                Spacer()
                Button("Delete") {
                    context.delete(recipe) // 删除模型
                }
            }
        }
    }
}

保存更改

如果自动保存被禁用,您可以手动保存更改或使用 rollback() 来放弃未保存的更改。

import SwiftData

struct RecipeDetailView: View {
    @Environment(\.modelContext) private var context
    @Query private var recipes: [Recipe]
    var body: some View {
        Button("Save Changes") {
            do {
                try context.save() // 手动保存更改
            } catch {
                print("Failed to save context: \(error)")
            }
        }
    }
}

如何不需要错误信息,可以通过下面方式保存更改

Button("Save Changes") {
    try? context.save() // 手动保存更改
}

手动创建新上下文时,自动保存通常是禁用的。可以通过调整 autosaveEnabled 属性来启用自动保存。如下所示

let newContext = ModelContext(container)
print(newContext.autosaveEnabled)  // 查看自动保存状态
newContext.autosaveEnabled = true  // 启用自动保存

总结

通过实例展示了如何使用 ModelContext 进行模型的插入、更新、删除和保存操作。通过 @Environment(\.modelContext),您可以轻松访问和管理模型数据,确保应用的快速性和持久化存储保持同步。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容