Ciampo
Ciampo

Reputation: 143

Core data deleting rules

My database has 3 entities: photos, places (where photos are taken) and tags (of photos).

database

Each photo has a relationship to the place in which it has been taken. Each place has a set of photos taken in it.

Each photo has a set of tags, and each tag has a set of photos. This is a many-to-many relationship, because a single photo can have multiple tags, and a tag can be associated with multiple photos.

Now, I can't figure out the right deleting rules for this behaviour:

Any suggestion?

Upvotes: 3

Views: 773

Answers (2)

Ciampo
Ciampo

Reputation: 143

So, thank to Marcus, i've set all the deleting rules to Nullify, and then i wrote this code in the Photos's prepareForDeletion:

- (void)prepareForDeletion
{    
    //tag check: if this photo was the last associated with that tag, deletion !!
    for (Tag *tag in self.tags) {
        if ([tag.taggedPhotos count] == 1) {
            [self.managedObjectContext deleteObject:tag];
        } else {
            tag.photoCount = [NSNumber numberWithInt:[tag.photoCount intValue]-1];
        }
    }

    //place check: if this photo was the last associated with that place, deletion !!
    if ([self.whereTaken.photos count] == 1) {
        [self.managedObjectContext deleteObject:self.whereTaken];
    }
}

I have not deleted the numberOfPhotosTagged attribute, since i'm using it to sort the tags.

Upvotes: 1

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

First, the tag should not need a separate attribute to keep track of the number of photos. You can query the relationship for that count.

Second, you would want to set up a -prepareForDeletion in the Photo entity that checks to see if it is the only photo with a reference to the tag and then deletes it if that is true.

Likewise, when you delete the photo, in its -prepareForDeletion you can check to see how many photos are in that place and invoke the same logic.

In the model itself I would then set the delete rule to just be nullify.

Upvotes: 2

Related Questions