开发者

Core Data loading in background problem

I have setup few methods to load core data in the background using NSOperationQueue, like the below:

operation = [[NSInvocationOperation alloc] initWithTarget:self                                                      
selector:@selector(selectToLoadDataOne) object:nil];

operation = [[NSInvocationOperation alloc] initWithTarget:self                                                      
selector:@selector(selectToLoadDataTwo) object:nil];

The "selectToLoadDataOne" and "selectToLoadDataTwo" is just standard NSFetchRequest using the template NSManagedContext from app delegate. Problem is that after loading a few times, it just stop loading altogether and stuck at executeFetchRequest: and without any error.

I know this is related to using of threads with core data, and so I tried 开发者_StackOverflow中文版to create a new nsmanagedobjectcontext for each call but the result returned are empty nsmanagedobject.

Can someone point me to a good example or doc I can use to solve the loading of core data from background thread?


Core Data has very specific rules about running on multiple threads. You must have one NSManagedObjectContext per thread and the thread that a NSManagedObjectContext will be used on must be the thread that creates it.

You are running into issues because you are breaking that rule.

Instead of using a NSInvocationOperation:

  1. create a subclass of NSOperation
  2. pass in the NSPersistentStoreCoordinator
  3. create the NSManagedObjectContext in the -main

Of course that is only going to load them into the NSPersistentStoreCoordinator and you are still going to need to reload them in the main NSManagedObjectContext.

Why do you need to load data on a background thread? Looking to speed up data loads is usually indicative of a deeper issue in the app.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜