ctietze
ctietze

Reputation: 2932

Core Data many-to-many cascade archival (trashing) for last child object

Say I have Project and Path. Project has many paths (optional). Paths can belong to many projects (non-optional, min=1). When I archive the last Project associated to a Path, the Path should be archived, too. When the Path belongs to another active project, though, it should not be archived.

"Archival" equals setting the archivedDate property.

My naive approach is this: the persistent stack subscribes to Core Data notifications (not sure which, though), checks affected Path objects upon saving, and enforces the archival rule.

What would you do to implement "cascade" archival?

Upvotes: 0

Views: 28

Answers (1)

Mundi
Mundi

Reputation: 80271

I think you could simply override setArchivedDate in your Project class. There you can check the status of all the paths and archive accordingly, something like

-(void)setArchivedDate:(NSDate*)newValue {
   [self willChangeValueForKey:@"archivedDate"];
   [self setPrimitiveValue:newValue forKey:"archivedDate"];
   [self didChangeValueForKey:@"archivedDate"];

   for (Path *path in self.paths) {
      NSSet *activeProjects = [path.projects filteredSetUsingPredicate: 
         [NSPredicate predicateWithFormat:@"archivedDate = nil"]];
      if (!activeProjects.count) {
         path.archivedDate = newValue;
      }
   }
}

PS: If you are using Swift, this is done in didSet.

Upvotes: 1

Related Questions