用核心数据实施foreach.onmove()

发布于 2025-02-12 12:54:28 字数 926 浏览 1 评论 0原文

我正在尝试使用核心数据实现foreach.onmove。我有两个实体,parent,与conder有一段经常的关系,并将其标记为有序。视图是这样的:

struct ParentView : View {
  @ObservedObject var parent : Parent

  var body : some View {
    List {
      ForEach($parent.children! as! [Child]) { child in 
        ChildView(child)
      }.onMove { 
        parent.managedObjectContext!.performAndWait { indices, to in
          (parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)
          try! parent.managedObjectContext!.save()
          parent.objectWillChange.send()
        }
      }
    }
  }
}

结果是:

  1. 没有任何错误。
  2. 在调试onMove函数期间,我可以看到根据需要重新订购这些项目
  3. ManageDobjectContext.upDateDobjects在同一调试步骤中为空,然后呼叫<<<代码> save()
  4. 重新加载应用程序时,重新订购显然没有保存(显然是因为更新>“更新”集合设置为#3。

我在做什么错?如何使MOC意识到重新排序的更改?

I am trying to implement ForEach.onMove using Core Data. I have two entities, Parent with a To-Many relationship to Child, with the relationship marked as Ordered. The view is something like this:

struct ParentView : View {
  @ObservedObject var parent : Parent

  var body : some View {
    List {
      ForEach($parent.children! as! [Child]) { child in 
        ChildView(child)
      }.onMove { 
        parent.managedObjectContext!.performAndWait { indices, to in
          (parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)
          try! parent.managedObjectContext!.save()
          parent.objectWillChange.send()
        }
      }
    }
  }
}

Results are:

  1. No errors of any kind.
  2. During debug of the onMove function, I can see that the items are re-ordered as required
  3. The managedObjectContext.updatedObjects is empty at the same debug step, before the call to save()
  4. When reloading the app, the re-ordering is obviously not saved (apparently because the updatedObjects set was empty at #3.)

What am I doing wrong? How can I make the MOC realize the re-ordering change?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪痕残 2025-02-19 12:54:29

我修复了这一点,显然是用一个简单的解决方案解决的。我将其发布给子孙后代的Google搜索者。 :d

问题与此行:

(parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)

显然,拿起不变的版本并使其可变起来,但没有更新托管对象。这有效:

parent.mutableOrderedSetValue(forKey: "children").moveObjects(at: indices, to: to)

I fixed this, apparently with a simple solution. I am posting this for future generations of google searchers. :D

The problem is with this line:

(parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)

Apparently, taking the immutable version and making it mutable works, but doesn't update the managed object. This works:

parent.mutableOrderedSetValue(forKey: "children").moveObjects(at: indices, to: to)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文