When to use fetch property in the core data with example in a cross-store scenario

1.3k Views Asked by At

I am facing same problem as here

How to achieve relationships between entity in one store with other?

Kindly guide me through this.

2

There are 2 best solutions below

0
On

It is indeed possible and makes total sense in some cases to split objects across stores

lets assume obj A in Store #1 and obj B in Store #2.
Each A has N Bs

easiest solution would maybe be a TRANSIENT property on A ... named 'allMyBs'
then implement the fetch in code:

- (NSArray*)allMyBs {
   NSFetchRequest *r == ... //setup to fetch Entity B
   [CoreDataHelper managedObjectContextForStore2] executeFetchRequest:r];
}

this isnt the fetched property yet but easy

see Cross-Store weak relationship with Fetched Properties? for a complicated way ^^

1
On

The short answer is that you can't. You can't have a relationship between managed objects that crosses persistent stores.

You can, however, implement a key or identifier in your model that YOU maintain across stores, and use that find 'related' objects in different stores.

If you have user records in one store, and application data in another, the application records might have a "belongsTo" property whose value is a user ID corresponding to a user record in the user store.

Apple's documentation is very specific about this:

From the Core Data Programming Guide: "Core Data does not let you create relationships that cross stores. If you need to create a relationship from objects in one store to objects in another, you should consider using fetched properties."

Again, from the Core Data Programming Guide: "You must be careful not to create relationships from instances in one persistent store to instances in another persistent store, as this is not supported by Core Data. If you need to create a relationship between entities in different stores, you typically use fetched properties (see “Fetched Properties”)."

This is exactly what I am talking about above. If you implement fetched properties that way, it is up to you to maintain the integrity of the graph. The same document walks you through creating and using fetched properties. Perhaps you can be more specific in what you need answered.