【发布时间】:2021-07-19 22:48:04
【问题描述】:
我的第一次尝试是在.onAppear 中设置属性包装器的nsPredicate 动态属性,但如果视图因任何原因重新初始化,.onAppear 设置的谓词将丢失。所以我又回到了使用初始化模式。
这是我认为应该有效(但没有)和有效(但神秘)的东西:
struct ItemEditView : View {
var item: Item
@FetchRequest(fetchRequest: Attribute.fetchRequestAllInOrder(), animation: .default)
var attributes: FetchedResults<Attribute>
init(item: Item) {
self.item = item
// This is how I would have expected to set the dynamic property at View initialization, however
// it crashes on this statement
attributes.nsPredicate = NSPredicate(format: "item == %@", item)
// Not sure why the below works and the above does not.
// It seems to work as desired, however it receives this runtime warning:
// "Context in environment is not connected to a persistent store coordinator"
$attributes.projectedValue.wrappedValue.nsPredicate = NSPredicate(format: "item == %@", item)
}
var body: some View {
List {
ForEach(attributes) { attribute in
Text("Name:\(attribute.name) Order:\(attribute.order)")
}
}
}
}
那么,为什么第一个赋值给 nsPredicate 会崩溃?在注释掉第一个之后,为什么第二个有效?警告信息是一个真正的问题吗?有一个更好的方法吗?似乎应该有一种使用新动态属性的简单方法来执行此操作。
【问题讨论】:
-
你为什么要获取
item?只需包装传递的值@ObservedObject var item: Item -
崩溃时的错误信息是什么?
-
崩溃是:线程1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
-
抱歉,物品太多...实际上,我不是在取物品。我正在获取与传递到视图中的项目相关的所有属性。 Attribute 实体与名为“item”的 Item 实体有关系。
-
难道你没有从 Item 到 Attribute 的反向关系,因为那样你就不需要 fetch 请求。您的列表将类似于
ForEach(item.attributes) { attribute in假设反向关系的名称是attributes
标签: core-data swiftui nspredicate