Question

I have a Core Data model similar to this:

enter image description here

When a Webgallery or Article object gets saved, it may use one or many pictures. They can use the same photographical subject but maybe in different sizes. I don't save pictures that don't get used in either a WebGallery or an Article.

Picture's relationships instance and social are set to cascade, so when the Picture object gets deleted, the corresponding PictureInstance and Social objects get deleted too.

1) Is there any way to know when a picture doesn't get used anymore, neither by WebGallery nor by Article so it can be deleted?

2) Is it a problem that the relationships previewPicture and teaserPicture don't have an inverse?

Was it helpful?

Solution

You should have an inverse for the relationship. With the inverse, the question becomes trivial. When a simple cascade rule will delete them from WebGallery and Article. (or perhaps you just want to nullify).

You should typically model relationships in both directions, and specify the inverse relationships appropriately. Core Data uses this information to ensure the consistency of the object graph if a change is made (see “Manipulating Relationships and Object Graph Integrity”). For a discussion of some of the reasons why you might want to not model a relationship in both directions, and some of the problems that might arise if you don’t, see “Unidirectional Relationships.”

(Core Data Programming Guide)

You can simply check if a picture is used whenever you delete it from a gallery or article:

[gallery removePictureObject:pictureToRemove];
if (pictureToRemove.galleries.count == 0 && pictureToRemove.articles.count == 0) {
    [managedObjectContext deleteObject:pictureToRemove];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top