Search code examples
iosmultithreadingcore-datagrand-central-dispatchnsmanagedobjectcontext

how to prevent main thread ios from killing background thread


I have a method in my AppDelegate that saves a NSManagedObjectContext passed as a parameter. This method may be called on either the main thread or a background thread, and I want to ensure that when this method is called the main thread doesn't kill it halfway through when the user terminates the program or what have you. How do I prevent the main thread from killing this thread when this method is being executed?

I also want to do this for writing data to a plist file -- this also may happen outside of the main thread.

I am doing all my background work by way of GCD and dispatch_async


Solution

  • Brad Larson had some suggestions on this post that should help you.

    In your appDelegate, when your app is getting pushed to the background, it calls applicationDidEnterBackground. From this routine, you can see if your method is currently in progress, and can behave accordingly.

    Depending on how long your task takes to run there are two options:

    1. If it will take significantly less than 5 seconds, you can just have your applicationDidEnterBackground wait until your task is completed before releasing. If you take longer than 5 seconds, your app will just get force-killed.

    2. If it could be a while, you can try beginBackgroundTaskWithExpirationHandler: to start a background task that finishes off your task.