在视图中附加了模型容器的Query()显示错误,说它没有模型容器。

huangapple go评论113阅读模式
英文:

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&#39;s environment to use Query

Any idea on what I might be doing wrong?
The code is basically this:

let currentTrainPredicate = #Predicate&lt;Train&gt; { 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&lt;Train&gt;(predicate: currentTrainPredicate) 
let currentTrain = try modelContext.fetch(descriptor).first

huangapple
  • 本文由 发表于 2023年8月11日 03:49:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定