Rog
Rog

Reputation: 18670

Core Data relationships, multiple managed object contexts & threads

This is a bit of a tricky one.

I have Document entities that are currently being imported into CoreData from a SQLite database on a background thread. There's a separate context for the background thread and I am batching the save at every 500 entries.

Saving the background thread context triggers a notification which grabs my main thread's contexts and performs a merge between the two.

Everything works as expected if I am only importing document entities.

My problem occurs when I try and establish a relationship between the current document being created, an another entity called briefcase.

This is what my import routine currently does:

I know that if I remove the call to reset the context after saving it, everything works as expected but my memory footprint goes way up and it is not something I am prepared to accept.

So my question is:

Your thoughts are very much appreciated. Rog

Upvotes: 0

Views: 780

Answers (1)

Rog
Rog

Reputation: 18670

Answering my own question:

  • Create Briefcase entity
  • Loop through SQLite database rows and create Document entities for each row
  • Create the relationship between the document in the loop and the briefcase entity
  • At every 500 rows, save context & immediately store the objectID for Briefcase after saving
  • Now it's ok to reset the context
  • (Re)retrieve the briefcase instance using the objectID saved above and the existingObjectWithID:error: method
  • Loop continues...

Upvotes: 1

Related Questions