我正在尝试理解新的SwiftData框架。只要我在SwiftUI视图中做所有事情,让它工作起来就很容易。我试图成为一名优秀的编码员,并将数据与UI分离,但无法连接到ModelContainer,而ModelContext是一个类文件。
下面是一个可以按原样运行的示例:
型号:
@Model
final public class Thing: Identifiable {
let myID = UUID()
var name: String
var comment: String
init(name: String, comment: String) {
self.name = name
self.comment = comment
}
}//struct
ContentView:将按钮中的代码更改为Create 10 Test Records以使用VM版本。
struct ContentView: View {
@StateObject var contentVM = ContentViewModel()
@Environment(\.modelContext) private var context
@State private var name: String = ""
@State private var comment: String = ""
@State private var selection: Thing?
@Query(sort: \.name) var things: [Thing]
var body: some View {
NavigationStack {
VStack(alignment: .leading) {
Text("Name:")
.padding(.leading, 12)
TextField("name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 5, leading: 10, bottom: 0, trailing: 10))
Text("Comment:")
.padding(.leading, 12)
TextField("comment", text: $comment)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 5, leading: 10, bottom: 0, trailing: 10))
}//v
.padding()
VStack(spacing: 20) {
Button(action: {
let thing = Thing(name: name, comment: comment)
context.insert(object: thing)
}, label: {
Text("Save")
})
Button(action: {
//contentVM.createThingsForTestVM(count: 10)
createThingsForTest(count: 10)
}, label: {
Text("Create 10 Test Records")
})
}//v buttons
Divider()
List {
ForEach(things) { thing in
Text(thing.name)
}
.onDelete(perform: deleteThings(at:))
}//list
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button {
deleteAllThings()
} label: {
Image(systemName: "trash")
}
}//group
}//toolbar
}//nav stack
}//body
private func deleteThings(at offsets: IndexSet) {
withAnimation {
offsets.map { things[$0] }.forEach(deleteThing)
}
}//delete at offsets
private func deleteThing(_ thing: Thing) {
//Unselect the item before deleting it.
if thing.objectID == selection?.objectID {
selection = nil
}
context.delete(thing)
}//delete things
private func deleteAllThings() {
for t in things {
if t.objectID == selection?.objectID {
selection = nil
}
context.delete(t)
}
}//delete all things
private func createThingsForTest(count: Int) {
for i in 0..<count {
let t = Thing(name: "Name " + String(i), comment: "Comment " + String(i))
context.insert(object: t)
}
do {
try context.save()
} catch {
print(error)
}
}//create things
}//struct content view
ContentViewModel:这确实会创建记录,但它不会更新UI,对我来说这似乎是错误的方法。我试图在初始化器中设置ModelContainer和ModelContext,但根本无法实现。
class ContentViewModel: ObservableObject {
init() {}
@MainActor
func createThingsForTestVM(count: Int) {
do {
let container = try ModelContainer(for: Thing.self)
let context = container.mainContext
for i in 0..<count {
let t = Thing(name: "Name " + String(i), comment: "Comment " + String(i))
context.insert(object: t)
}
try context.save()
} catch {
print("Could not create a container \(error.localizedDescription)")
}
}//create things
}//class
任何指导将不胜感激。Xcode 15.0 Beta(15A5160n),iOS17.0
2条答案
按热度按时间iklwldmw1#
在SwiftUI中,View结构已经与UI分离,View结构层次结构应该是视图数据的主要封装机制。
SwiftUI区分这些结构,并自动为您创建/更新/删除UI对象,即它管理实际的视图层或MVC中的V。
因此,您只需移除自定义视图模型对象,并按设计使用View结构和属性 Package 器。
StateObject用于当你想要在一个State中引用类型时,比如你正在做一些异步的事情,而生命周期绑定到屏幕上的某个东西。现在我们有了async await和任务修饰符it在大多数情况下不再需要。
2skhul332#
我也在纠结同样的事情-我注意到一件事:
而不是:
尝试: