英文:
Query() in view with model container attached shows error saying it does not have a model container
问题
我在视图上有一个函数,它的环境中有一个 modelContext
,并且可以成功地向模型容器添加数据。但是当我在同一个函数中尝试运行 Query()
函数调用时,我在控制台上收到以下消息:
在视图的环境中设置 .modelContext 以使用 Query
对于我可能做错了什么,有什么想法吗?
代码基本如下:
let currentTrainPredicate = #Predicate<Train> { train in
train.number == currentTrainNumber
}
// 如果存在该值,则更新它
if let currentTrain = Query(filter: currentTrainPredicate).wrappedValue.first {
currentTrain.dateViewed = Date()
} else {
self.train.dateViewed = Date()
modelContext.insert(self.train)
}
英文:
I have a function on a view that has a modelContext
on its environment and that can successfully add data to the model container. But when in that same function I try to run a Query()
function call I get this message on the console:
Set a .modelContext in view's environment to use Query
Any idea on what I might be doing wrong?
The code is basically this:
let currentTrainPredicate = #Predicate<Train> { train in
train.number == currentTrainNumber
}
// Update the value if it exists
if let currentTrain = Query(filter: currentTrainPredicate).wrappedValue.first {
currentTrain.dateViewed = Date()
} else {
self.train.dateViewed = Date()
modelContext.insert(self.train)
}
答案1
得分: 1
让我来帮你翻译这段代码:
如果你在一个函数中进行这个操作,那么请使用 [FetchDescriptor](https://developer.apple.com/documentation/swiftdata/fetchdescriptor) 而不是一个 Query,因为 @Query 是一个属性包装器,所以你只在声明属性时使用它。
let descriptor = FetchDescriptor<Train>(predicate: currentTrainPredicate)
let currentTrain = try modelContext.fetch(descriptor).first
英文:
If you are doing this in a function then use a FetchDescriptor instead of a Query since @Query is a property wrapper so you only use it when declaring a property.
let descriptor = FetchDescriptor<Train>(predicate: currentTrainPredicate)
let currentTrain = try modelContext.fetch(descriptor).first
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论