是否可以在Core Data中自动删除未引用的对象?

发布于 2025-01-04 09:42:50 字数 292 浏览 1 评论 0原文

我的数据模型包含两个实体:作者和书籍,具有一对多关系(一位作者可能写多本书)。

假设数据库中只有两本书和两位作者,如下所示:

  • 书 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 技术交流群。

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

发布评论

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

评论(2

留一抹残留的笑 2025-01-11 09:42:50

查看“删除传播”。它就是为了解决这个问题而存在的。

如果这不能完全满足您的要求:您可以在 Book 实体上覆盖 - (void)prepareForDeletion ,然后检查是否有任何已在上下文中注册并有待更改的作者(因为它们的逆会发生变化)并且没有书籍:

{
    // ...
    [[NSNotificationCenter defaultNotificationCenter] addObserver:self selector:@selector(deleteOrphanedAuthors:) name:NSManagedObjectContext object:moc];
    // ...
}

- (void)deleteOrphanedAuthors:(NSNotification *)note;
{
    NSManagedObjectContext *moc = [note object];
    NSManagedObjectModel *mom = [[moc persistentStoreCoordinator] managedObjectModel];
    NSEntityDescription *authorEntity = [[mom entitiesByName] objectForKey:@"Author"];
    for (NSManagedObject *author in [moc updatedObjects]) {
        if ([author entity] == authorEntity) {
            if (![author hasFaultForRelationshipNamed:@"books"] && ([[author books] count] == 0)) {
                [moc deleteObject:author];
            }
        }
    }
}

注意:您可以传递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:

{
    // ...
    [[NSNotificationCenter defaultNotificationCenter] addObserver:self selector:@selector(deleteOrphanedAuthors:) name:NSManagedObjectContext object:moc];
    // ...
}

- (void)deleteOrphanedAuthors:(NSNotification *)note;
{
    NSManagedObjectContext *moc = [note object];
    NSManagedObjectModel *mom = [[moc persistentStoreCoordinator] managedObjectModel];
    NSEntityDescription *authorEntity = [[mom entitiesByName] objectForKey:@"Author"];
    for (NSManagedObject *author in [moc updatedObjects]) {
        if ([author entity] == authorEntity) {
            if (![author hasFaultForRelationshipNamed:@"books"] && ([[author books] count] == 0)) {
                [moc deleteObject:author];
            }
        }
    }
}

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.

記憶穿過時間隧道 2025-01-11 09:42:50

您需要手动确定“孤儿”书籍。

当您更新作者关系时,您可以检查旧作者的书籍关系以查看它是否仍然有任何书籍。

或者,您可以使用通知来确定 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 to Author objects. Have a look at that specific notification in the docs.

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