Deletions in a many-to-many structure

不羁岁月 提交于 2019-12-03 10:47:14

Nullify is sufficient, and many-to-many sounds right. The specific constraint you want (deleting orphans) is not directly enforceable by core data, though, so you get to do a little cleanup yourself.

Specifically, implement willSave in your entity classes, and have each entity test: am I not deleted; and, do I have no associated (products/catalogs)? If so, delete myself. (the not-deleted test is important to avoid an infinite loop of willSaves.)

This postpones the deletion of the orphaned catalogs or products until save time. This is probably not a problem.

JosephH

I've implemented rgeorge's answer, and thought the exact code might be helpful to other people:

- (void)willSave
{
    [super willSave];

    if (self.isDeleted)
        return;

    if (self.products.count == 0)
        [self.managedObjectContext deleteObject:self];
}

Swift translation of Andy and JosephH

override func willSave() {
    super.willSave()

    if self.deleted {
      return
    }

    if self.products.count == 0 {
      self.managedObjectContext?.deleteObject(self)
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!