添加一对多关系而不更新 UI
我在 plan 的核心数据中有一对多关系 -> 食谱。 plan.recipes 的类型为 NSSet?,因此我创建了带有计算属性的自定义 NSManagedObject 类,以将它们转换为数组,并添加了一个额外的属性 recipesArray >:
public var recipesArray: [Recipe] {
let set = recipes as? Set<Recipe> ?? []
return set.sorted {
$0.wrappedName < $1.wrappedName
}
}
然后,我使用 ForEach 在视图中显示此列表,并使用 recipesArray 属性。该视图的子视图调用 plan.addToRecipes(recipe: Recipe) 来向关系添加新对象。然后我保存。
问题是,父视图中的 ForEach 不会对此添加做出反应。如果我通过导航刷新视图,则会显示新菜谱,但添加新菜谱时视图不会自动更新。
有谁知道该怎么做?我应该使用原始的 recipes 属性而不是这个自定义数组属性吗?
I have a one-to-many relationship in core data of plan -> recipe. plan.recipes is of type NSSet?, so I have created custom NSManagedObject classes with computed properties to convert these into arrays, adding an extra property recipesArray:
public var recipesArray: [Recipe] {
let set = recipes as? Set<Recipe> ?? []
return set.sorted {
$0.wrappedName < $1.wrappedName
}
}
I then display this list in a View using a ForEach, using the recipesArray property. A subview of this view calls plan.addToRecipes(recipe: Recipe), to add a new object to the relationship. I then save.
The issue is, the ForEach in the parent view does not react to this addition. If I refresh the view by navigating away, then the new recipe is shown, but the View is not automatically updated when the new recipe is added.
Does anyone know how to do this? Should I be using the original recipes property instead of this custom array one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用等于给定
计划
的谓词为Recipe
创建另一个FetchRequest
,例如:注意:当前有一个
FetchRequest
中的错误导致主体始终被调用,即使此View
使用相同的plan
进行初始化,因此也是相同的FetchRequest
>。这是因为FetchRequest
结构每次都会在其中初始化一个新对象,导致它以及该 View 显示为更改为 SwiftUI。我报告了此错误,希望他们能修复它。同时,您可以使用包装器View
来解决这个问题,该包装器将plan
作为 let,这样主体就不会被调用。You need to make another
FetchRequest
forRecipe
s using a predicate that equals a givenplan
, e.g. something like this:Note: There is currently a bug in
FetchRequest
that results in body always invoked even when thisView
is init with the sameplan
and thus sameFetchRequest
. This is because theFetchRequest
struct inits a new object inside it every time, causing it and consequently this View to appear as changed to SwiftUI. I reported this bug so hopefully they fix it. You could workaround it in the meantime with a wrapperView
that takes theplan
as a let so body won't be called.