I have a CoreData application with dynamic data that is updated once a day via a server.
The update is handled in a seperate class and in the AppDelegate I write:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.updater = [[Updater alloc] init];
...
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[updater checkForUpdatesInContext:[self managedObjectContext]];
}
The checkForUpdatesInContext checks whether a day has passed or not and then does the updating process.
Now this way of course it would run on the main thread, and if an update is going on, the app would “freeze” until the update is done, which could take a while, since new objects are created and there’s also images involved. So my idea was to run this on a background thread or on a second thread or whatever Objective-C offers.
My question: What would be the most efficient way to get checkForUpdatesInContext off the main thread and how to go about it? The apple docs are (as usual) somewhat confusing.
Getting the update operation to happen in a background thread isn’t that tricky e.g.
or if you are looking for the ability to cancel the background thread, read up on NSOperation and NSOperationQueue.
Your problem is going to be dealing with multithreading and CoreData 🙂 You need to read this guide. Basically, you need to make sure that your background thread doesn’t use the same NSManagedContext (it must create a new one from the same NSPersistentStore) and doesn’t pass NSManagedObjects between threads (i.e. only pass object IDs back to the UI thread, not the objects themselves).