Alex
Alex

Reputation: 5278

CoreData - NSManagedObject SubObject Only Stored in one Object at a time

I have two CoreData Entities: List and Item. List contains a relationship with a destination of Item. It is a to-many relationship (List entities can contain many Items)

List = {
  id: String,
  name: String
  items: <Item>
}

Item = {
  id: String,
  name: String
}

Now, let's say we have:
2 total Lists -> List_1 and List_2
3 total Items: Item_1, Item_2, and Item_3.

The lists looks like:

List_1 = {
  id: "1001",
  name: "Foo"
  items: <Item_1, Item_2>
}

List_2 = {
  id: "1002",
  name: "Bar"
  items: <Item_2, Item_3>
}

When I make a fetch against CoreData I am experiencing inconsistent results, and the inconsistency is based on the last List that was loaded in the app.

For example, if I use the app and the last list I load is List_1 when I query to get all the items in List_1 I am returned:

Item_1, Item_2

HOWEVER, if I use the app and the last list I load is List_2 when I query to get all the items in List_1 I am returned:

Item_1 (only....NO Item_2?!) as if it was "moved" out of List_1 and into List_2 since List_2 is the last list that was visited that contained `Item_2.

Are CoreData objects that are stored as part of a one-to-many relationship only allowed to exist in one CoreData object at a time? Does anybody see something wrong with how I am approaching this?

Any help is appreciated! Thanks

Upvotes: 2

Views: 113

Answers (1)

Icaro
Icaro

Reputation: 14845

It seems that you have a one to many relationship between List and items:

List <-->>Items

One to Many

that mean one list can have many items but one item can have just one list.

But you want the items to be able to belong to many lists, so you need to create a many to many relationship between list and items

List <<-->>Items

In this case one list can have many Items but one Item can belong to many lists.

Many to Many

I hope that helps

Upvotes: 3

Related Questions