0

I have created a singleton class that accesses a datastore and returns an object representing a Core Data entity. This is fine in the normal thread but I am concerned about accessing this singleton method from another class running on a background thread as the background thread will be running with its own copy of the Managed Object Context.

When trying to call the singleton from the background thread do I need to create a fresh instance of the singleton and pass in the background thread's copy of the managed object context or can I safely access the singleton method and allow that to use the shared managed object context that it retrieves internally from the app delegate please?

Craig Moore
  • 1,093
  • 1
  • 6
  • 15
  • "fresh instance of the singleton" How is this supposed to happen? – Abizern Jan 25 '14 at 13:15
  • Instanciating the singleton through the init event, it gives you a non-singleton copy – Craig Moore Jan 25 '14 at 15:24
  • Then what is the point of having a singleton? If you are going to just create your own whenever you want - what is the point of having a singleton in the first place? – Abizern Jan 25 '14 at 15:36
  • The idea is to have a singleton access method to simplify data access when accessing from the main thread. I would like to continue that access method in a background thread, but if it is not possible you can instanciate it and set the managed object context in the instance you create to prevent thread conflicts – Craig Moore Jan 25 '14 at 16:07

1 Answers1

2

Have your data manager class make all the relevant Core Data calls with performBlock: or performBlock:andWait:

That way the calls will always be made in a thread safe manner.

Personally, however, I usually write my data manager so that It is called on the main thread, and it takes care of making any further calls on whatever thread makes sense.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • If you perform it on the main thread don't you get UI blocking? – Craig Moore Jan 25 '14 at 15:25
  • Not if the data manager then makes the actual calls on a background thread. My point is that you have a data-manager object. It should be up to that object to perform it's operations on background on foreground threads as is most efficient. – Abizern Jan 25 '14 at 15:35
  • I will be honest. I had never considered that approach. I currently start the background thread from the view controller and call the data manager from that. I thank you for your advice, it will take me a while to digest this idea and assess it so I will mark your answer as the correct answer and go away and think about this. Thank you . – Craig Moore Jan 25 '14 at 16:09
  • Here are some slides from a talk by Marcus Zarra which describe an implementation of a non-singleton data manager http://www.iosdevuk.com/storage/talks2013/MarcusZarraMVC-N.pdf – Abizern Jan 25 '14 at 16:44