Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: What happens if I execute a background job and then leave the view controller?

Let's say I have view controller A and view controller B.

In VC A, I push VC B. Then in VC B, I execute some background tasks using NSOperation. In the background tasks, I modify VC B's variables.

What happens if the background tasks are not finished and I quit VC B? Will the operations be cancelled or will they still be executing? When debugging, it seems like they are still executing. In that case, wouldn't they be accessing already released variables (since I quitted VC B).

I'm a bit confused by this, anyone can clear me up? :)

Thanks,

like image 642
Van Du Tran Avatar asked Feb 15 '12 21:02

Van Du Tran


People also ask

Will iOS terminate the app running in background after a specific time?

At the same time, didReceiveMemoryWarning is invoked for the app. At this point, so that your app continues to run properly, the OS begins terminating apps in the background to free some memory. Once all background apps are terminated, if your app still needs more memory, the OS terminates your app.

What happens when app goes to background in iOS?

After your app enters the background and your delegate method returns, UIKit takes a snapshot of your app's current user interface. The system displays the resulting image in the app switcher.

Should I let apps run in the background Iphone?

It is a common belief that you should close apps running in background to improve performance and save battery life. Unfortunately, this is a myth that is not true in almost all situations.

How can we handle background operations iOS?

Use the BackgroundTasks framework to keep your app content up to date and run tasks requiring minutes to complete while your app is in the background. Longer tasks can optionally require a powered device and network connectivity. Register launch handlers for tasks when the app launches and schedule them as required.


1 Answers

You are correct, the operation does not magically disappear just because the object that spawned it did.

You will cause the OS to throw an exception as it tries to access the now deallocated view controller object. This is the danger of doing background threaded operations.

You need to plan accordingly, in this case, be able to cancel your operation when VC B gets deallocated. This means subclassing the NSOperation, implementing main() and checking for isCancelled.

See Apple's documentation regarding NSOperation, NSOperationQueues, and Concurrency Programming.

like image 64
gschandler Avatar answered Oct 19 '22 23:10

gschandler