开发者

Core Data relationships, multiple managed object contexts & threads

This is a bit of a tricky one.

I have Document entities that are currently bein开发者_Go百科g 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:

  • Create Briefcase entity
  • Loops through SQLite database rows and creates Document entities for each row
  • Create the relationship between the document in the loop and the briefcase entity
  • At every 500 rows, I save & reset the context. This triggers a ContextSave notification which grabs the main thread and merges with the main thread's context.
  • This is where my issue is: after the save & reset above, my Briefcase entity gets merged with the main thread so when my loop continues, the next document entity created tries to associate itself with the briefcase, which is where I get a crash saying I can't establish relationships between objects on separate threads.

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:

  • Can you think of a way of keeping the Briefcase entity around (and valid) for the entire import process so I can continue to create the relationships?

  • My first thought was to create the briefcase entity without a context and then add it to the context once the whole process is finished. This didn't work very well (it crashed on creation).

Your thoughts are very much appreciated. Rog


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜