Does every Core Data Relationship have to have an Inverse?
Let’s say I have two Entity classes:
SocialApp I have one Attribute:
appURL and one Relationship:
SocialAppType I have three Attributes:
The destination of the
type is a single record in
As an example, for multiple Flickr accounts, there would be a number of
SocialApp records, with each record holding a link to a person’s account. There would be one
SocialAppType record for the “Flickr” type, that all
SocialApp records would point to.
When I build an application with this schema, I get a warning that there is no inverse relationship between
/Users/username/Developer/objc/TestApp/TestApp.xcdatamodel:SocialApp.type: warning: SocialApp.type -- relationship does not have an inverse
Do I need an inverse, and why?
- Using Swift protocols with generics
- How to delete an old/unused Data Model Version in Xcode
- Which way to store data(image)? NSData, String or Transformable
- How to access CoreData model in today extension (iOS)
- Z_PK Column in Core Data Database
- What is the new way of binding an NSArrayController to the managed object context of a Core Data document?
6 Solutions Collect From Internet About “Does every Core Data Relationship have to have an Inverse?”
In practice, I haven’t had any data loss due to not having an inverse – at least that I am aware of. A quick Google suggests you should use them:
An inverse relationship doesn’t just
make things more tidy, it’s actually
used by Core Data to maintain data
— Cocoa Dev Central
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
— Core Data Programming Guide
Apple documentation has an great example that suggest a situation where you might have problems by not having an inverse relationship. Let’s map it into this case.
Assume you modeled it as follows:
Note you have a to-one relationship called “type“, from
SocialAppType. The relationship is non-optional and has a “deny” delete rule.
Now consider the following:
SocialApp *socialApp; SocialAppType *appType; // assume entity instances correctly instantiated [socialApp setSocialAppType:appType]; [managedObjectContext deleteObject:appType]; BOOL saved = [managedObjectContext save:&error];
What we expect is to fail this context save since we have set the delete rule as Deny while relationship is non optional.
But here the save succeeds.
The reason is that we haven’t set an inverse relationship. Because of that, the socialApp instance does not get marked as changed when appType is deleted. So no validation happens for socialApp before saving (it assumes no validation needed since no change happened). But actually a change happened. But it doesn’t get reflected.
If we recall appType by
SocialAppType *appType = [socialApp socialAppType];
appType is nil.
Weird, isn’t it? We get nil for a non-optional attribute?
So you are in no trouble if you have set up the inverse relationship.
Otherwise you have to do force validation by writing the code as follows.
SocialApp *socialApp; SocialAppType *appType; // assume entity instances correctly instantiated [socialApp setSocialAppType:appType]; [managedObjectContext deleteObject:appType]; [socialApp setValue:nil forKey:@"socialAppType"] BOOL saved = [managedObjectContext save:&error];
I’ll paraphrase the definitive answer I found in More iPhone 3 Development by Dave Mark and Jeff LeMarche.
Apple generally recommends that you always create and specify the inverse, even if you don’t use the inverse relationship in your app. For this reason, it warns you when you fail to provide an inverse.
Relationships are not required to have an inverse, because there are a few scenarios in which the inverse relationship could hurt performance. For example, suppose the inverse relationship contains an extremely large number of objects. Removing the inverse requires iterating over the set that represents the inverse, weakening performance.
But unless you have a specific reason not to, model the inverse. It helps Core Data ensure data integrity. If you run into performance issues, it’s relatively easy to remove the inverse relationship later.
The better question is, “is there a reason not to have an inverse”? Core Data is really an object graph management framework, not a persistence framework. In other words, its job is to manage the relationships between objects in the object graph. Inverse relationships make this much easier. For that reason, Core Data expects inverse relationships and is written for that use case. Without them, you will have to manage the object graph consistency yourself. In particular, to-many relationships without an inverse relationship are very likely to be corrupted by Core Data unless you work very hard to keep things working. The cost in terms of disk size for the inverse relationships really is insignificant in comparison to the benefit it gains you.
There is at least one scenario where a good case can be made for a core data relationship without an inverse: when there is another core data relationship between the two objects already, which will handle maintaining the object graph.
For instance, a book contains many pages, while a page is in one book. This is a two-way many-to-one relationship. Deleting a page just nullifies the relationship, whereas deleting a book will also delete the page.
However, you may also wish to track the current page being read for each book. This could be done with a “currentPage” property on Page, but then you need other logic to ensure that only one page in the book is marked as the current page at any time. Instead, making a currentPage relationship from Book to a single page will ensure that there will always only be one current page marked, and furthermore that this page can be accessed easily with a reference to the book with simply book.currentPage.
What would the reciprocal relationship be in this case? Something largely nonsensical. “myBook” or similar could be added back in the other direction, but it contains only the information already contained in the “book” relationship for the page, and so creates its own risks. Perhaps in the future, the way you are using one of these relationships is changed, resulting in changes in your core data configuration. If page.myBook has been used in some places where page.book should have been used in the code, there could be problems. Another way to proactively avoid this would also be to not expose myBook in the NSManagedObject subclass that is used to access page. However, it can be argued that it is simpler to not model the inverse in the first place.
In the example outlined, the delete rule for the currentPage relationship should be set to “No Action” or “Cascade”, since there is no reciprocal relationship to “Nullify”. (Cascade implies you are ripping every page out of the book as you read it, but that might be true if you’re particularly cold and need fuel.)
When it can be demonstrated that object graph integrity is not at risk, as in this example, and code complexity and maintainability is improved, it can be argued that a relationship without an inverse may be the correct decision.
While the docs don’t seem to require an inverse, I just resolved a scenario that did in fact result in “data loss” by not having an inverse. I have a report object that has a to-many relationship on reportable objects. Without the inverse relationship, any changes to the to-many relationship were lost upon relaunch. After inspecting the Core Data debug it was apparent that even though I was saving the report object, the updates to the object graph (relationships) were never being made. I added an inverse, even though I don’t use it, and voila, it works. So it might not say it’s required but relationships without inverses can definitely have strange side effects.
- Restrictions around Protocols and Generics in Swift
- Play socket-streamed h.264 movie on iOS using AVFoundation
- “This bundle is invalid – The file extension must be .zip” error submitting to iTunes
- Where does xcode take application's Identifier from?
- How to convert string to date to string in Swift iOS?
- xcodebuild command in shell script iOS
- How to display HTML-like table data on iPhone?
- Stop UIWebView from “bouncing” vertically?
- How can I rearrange views when autorotating with autolayout?
- Facebook Get friends list
- iTunes Store operation failed. No suitable application records were found. Verify your bundle identifier ‘org.cocoapods.Alamofire’ is correct
- UIPopoverController's view controller gets resized after keyboard disappears
- can i change my iOS deployment target to 5.0 on xcode 4.5?
- How to get Date from String in swift 3?
- Swift's GeneratorOf<T> crazy init