是否可以在Core Data中自动删除未引用的对象?
我的数据模型包含两个实体:作者和书籍,具有一对多关系(一位作者可能写多本书)。
假设数据库中只有两本书和两位作者,如下所示:
- 书 A 分配给作者 X
- 书 B 分配给作者 Y
假设应用以下更改:
- 书 B 分配给新作者 Z。
结果:
- 作者 Y存在于数据库中但没有指向任何书。
我的问题:是否可以配置数据模型,以便像作者 Y 这样的对象在没有被任何书籍引用时自动删除?
My data model contains two entities: Author and Book with a one to many relationship (one author may write several books).
Let's say that there are only two books and two authors in DB as follows:
- Book A is assigned to Author X
- Book B is assigned to Author Y
Assuming following change is applied:
- Book B is assigned to a new Author Z.
Result:
- Author Y exists in DB but points to no book.
My question: is it possible to configure the data model so objects like Author Y will be automatically deleted when they are not referenced by any book?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看“删除传播”。它就是为了解决这个问题而存在的。
如果这不能完全满足您的要求:您可以在 Book 实体上覆盖
- (void)prepareForDeletion
,然后检查是否有任何已在上下文中注册并有待更改的作者(因为它们的逆会发生变化)并且没有书籍:注意:您可以不传递
nil
作为要观察的对象(即上下文) ,因为您使用的框架可能有自己的上下文,并且您不想弄乱它们。另外,请注意此代码如何小心地避免在发生错误时触及
author
对象。如果删除一本书,Core Data 将更改相应作者对象的反向关系,从而使该关系出现故障,从而不再是故障。并且代码只会对这些对象进行操作。Check out "delete propagation". It's there to solve exactly that problem.
If that doesn't do exactly what you want / need: You can override
- (void)prepareForDeletion
on the Book entity and at that point check for any Authors that are registered with the context and have pending changes (since their inverse will have changed) and have no books:Note: You can not pass
nil
as the object (i.e. context) to observe, since frameworks you use, might have their own context, and you do not want to mess with them.Also, note how this code is careful not to touch the
author
object if it's a fault. If a book is deleted, Core Data will change the corresponding author objects' inverse relationships, hence fault in that relationship, such that it is no longer a fault. And the code will only operate on those objects.您需要手动确定“孤儿”书籍。
当您更新作者关系时,您可以检查旧
作者
的书籍关系以查看它是否仍然有任何书籍。或者,您可以使用通知来确定
NSManagedObjectContext
何时更改:NSManagedObjectContextObjectsDidChangeNotification
。如果您注册此通知,您可以检查Author
对象的许多更改。看看文档中的具体通知。You will need to determine "orphaned" books manually.
When you update the Author relationship you could check the old
Author
's books relationship to see if it still has any books.Alternatively you could use notifications to determine when the
NSManagedObjectContext
changes:NSManagedObjectContextObjectsDidChangeNotification
. If you register for this notification you can check for a number of changes toAuthor
objects. Have a look at that specific notification in the docs.