0

The scenario is

  1. I want to pass NSManagedObject across thread.
  2. The NSManagedObject I want to pass is temporary, which means that I don't want to store it in CoreData.

Currently, I have two solutions:

  1. Create a normal NSManagedObject, do something, store it in CoreData, and pass the permanent objectID to another thread, then delete it in another thread.

    [My concern]Efficiency is low to CoreData.

  2. Create a temporary NSManagedObject as this, do something, generate a NSDictioanry as this, and pass the NSDictioanry to another thread, then Create a temporary NSManagedObject and init with this NSDictionary in another thread.

    [My concern]I don't know how to init a NSManagedObject with a NSDictionary.

Any suggestion?

Community
  • 1
  • 1
Yuwen Yan
  • 4,777
  • 10
  • 33
  • 63

1 Answers1

-1

I would go with the first solution, i.e. saving the managed objects. The reason is because managed object IDs is the recommended way to share objects across contexts.

You could create your 1000 managed objects and save in batches of, say 200. I think you would be quite happy with the performance.

You could then delete the objects some time later when it is no longer time critical.

I would also not really object to the dictionary method. To create a managed object from a dictionary, the most obvious way would be to give the object class a custom initializer that takes a conforming dictionary as an argument.

If you generated the dictionary as you indicated, the keys will be the same keys as the attribute names of the managed object, so you would be just doing the reverse as in that solution.

Perhaps there is no one-liner shortcut, but something like this:

for (NSString *key in dictionary.allKeys) {
    [managedObject setValue:dictionary[key] forKey:key];
}
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • thanks! your answer is convincing, but I'd like to keep my question open and wait for other different suggestion, since I'm not looking for an answer but suggestion here. – Yuwen Yan May 17 '15 at 23:49
  • 1
    You have a main context and are trying to link to them from a background thread via managed objects. It has everything to do with thread safety. Do option 2. – Derek May 19 '15 at 02:40