objective-c swift - Does every Core Data Relationship have to have an Inverse?

ordered rule (6)

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.

Let's say I have two Entity classes: SocialApp and SocialAppType

In SocialApp I have one Attribute: appURL and one Relationship: type.

In SocialAppType I have three Attributes: baseURL, name and favicon.

The destination of the SocialApp relationship type is a single record in SocialAppType.

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 SocialAppType and SocialApp.

 /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?

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 integrity.

-- 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 Relationships.”

-- Core Data Programming Guide

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.

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 SocialApp to 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];

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.

There are two ways to insert data into Core Data - and whichever one you use is up to you. However, one of them depends on whether you have generated Model classes for your data model for the Core Data db.

The regular way is to use the following:

NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"table" 
[object setValue:@"value1" forKey:@"stringColumn"];
[object setValue:12 forKey:@"numberValue"];
NSError *error;
if (![context save:&error]) {
    NSLog(@"Failed to save - error: %@", [error localizedDescription]);

This is assuming you've already got your managed object context set up. It is much more efficient if you create and insert your objects into the context in a loop, and then save after the loop ends.

The other method isn't much different, but is much safer in terms of type safety. If you have generated model classes (which you can do from the xcdatamodels) then you can simply create an object of that class and set its properties.

TableObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"table" 
[object setStringColumn:@"value1"];
[object setNumberValue:12];
NSError *error;
if (![context save:&error]) {
    NSLog(@"Failed to save - error: %@", [error localizedDescription]);

To delete from a table, simply retrieve the object from the table (I'm assuming you are using the second method here for insertions, and as such have generated model classes) and use the following:

[context deleteObject:object];

Note that you will need to call save for that to take effect as well.

Hope this helps! Good luck!

EDIT: Sorry, I must've misread the question!

To examine an existing record, you'll want to create a Fetch Request, and then execute it on your managed object context. At bare minimum, a Fetch Request requires an entity (so it knows what table to search on). To specify search terms, you will need to create a predicate (otherwise the request will simply return everything in the table). You can also specify a set of sort descriptors so that your results will be sorted.

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"table" inManagedObjectContext:context];
[request setEntity:entity];

NSError *errorFetch = nil;
NSArray *array = [context executeFetchRequest:request error:&errorFetch];

This code creates a fetch request, and returns every object from the table named "table" in an array. From here, since all of the required objects are in the array, you can inspect and edit the records. If you make any changes, remember to save the context! The following loop logs the first value in each object, using the same table as the above examples.

for(TableObject *object in array)
    NSLog(@"object value1 = %@", object.value1);

You can also delete records from this point as well using the above mentioned function.

For more information about Fetch Requests, please give the class reference a look. I would also highly recommend reading about sort descriptors and predicates, since they're very important for searching your Core Data db, and certain uses of them are less efficient than others (particularly in the creation of NSPredicates).

Good luck!

objective-c core-data