问题
I have a very simple Core data Model comprising of a single Gallery which contains multiple Images. It seems to me that it should be enough for a Gallery to have a one-to-many relationship with Image, but if I don't also establish an inverse relationship from Image back to gallery I get Compiler warnings and errors. From an object-oriented perspective it seems to me that an Image shouldn't know or care if it is in a Gallery or any other ManagedObject so why does the compiler force me to create this inverse relationship? Having a 'gallery' property on the image seems very wrong.
回答1:
Core Data uses the inverse relationship to help maintain referential integrity. When you change a relationship or delete an object it speeds up performance dramatically. Without the inverse those same actions would potentially result in full table scans.
In my opinion, not having an inverse should be an error instead of a warning. The difference can be dramatic in some fairly common situations.
Just imagine a multi-entity cascade delete without them. Could take long enough that the OS thinks your app has crashed.
回答2:
I think you can't apply oo principles to database structures - they aren't in the same domain. Core Data is about tables and rows and pointers between them. Let's look at referential integrity and your gallery example. If you don't have a relationship from an image to a gallery, when you go to delete an image, the system will not know to remove its reference in the gallery. You could argue with some validity that this sort of detail should be taken care of, but I think you that's the way it is, and you should just live with it. Maybe send a bug report to Apple..
来源:https://stackoverflow.com/questions/7779464/why-does-an-entity-need-an-inverse