0

I have an HTTP call to a URL, which returns my data in JSON format, I parse it, then I have to load it in my Core Data context.

Now I am doing it (parsing - entities creation - commit) on the main thread, by using GCD (grand central dispatch) to dispatch a block on the main queue. The http call is asynchronous, so it's ok, but the db loading is not, so it freezes my user interface: a UITableView backed by a NSFetchedResultsController.

What I'd like to do, is making these last tasks on a secondary thread, but don't know how!

I heard something about creating a second context, using that on the secondary thread, then trash it and "refresh" the "main" context, don't know how to explain. Maybe is there a wwdc ed. video on this argument, too? I can't find valid documentation.

Can you help me, loading data in asynchronous way, so my table never stop scrolling?

Fabio B.
  • 9,138
  • 25
  • 105
  • 177
  • I just responded to a similar question here. It should have everything you need - http://stackoverflow.com/questions/7540801/coredata-and-threads-gcd/7545514#7545514 – Rog Sep 28 '11 at 11:11

1 Answers1

1

There is a rule: One context for one thread. Create new context in your not main queue and work with it.

Add observer for this context: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(<#Selector name#>) name:NSManagedObjectContextDidSaveNotification object:<#A managed object context#>];

After your parser is done and objects in context, save that context which will kick out notification. In main queue, catch this notification and on main queue context call - (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification.

user500
  • 4,519
  • 6
  • 43
  • 56
  • That solution does not work, can you help me out with a little more details please? The notification arrives, but it still freezes my gui for a few seconds – Fabio B. Oct 04 '11 at 06:06
  • just freezes for a few seconds during mergeChangesFromContextDidSaveNotification – Fabio B. Oct 05 '11 at 06:09
  • Well, this is how it should be done. I would try to find solution in another question... – user500 Oct 05 '11 at 17:56