Van Du Tran
Van Du Tran

Reputation: 6892

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,

Upvotes: 5

Views: 639

Answers (3)

Art Swri
Art Swri

Reputation: 2804

It would be good to consider the purpose of VC-B vs the purpose of the background activities. If the background activities are there to support what the user sees on VC-B, and when user moves away from VC-B the background activities are no longer relevant, then leaving VC-B should cause the background activities to cease. On the other hand if the background activities have a purpose 'larger than' VC-B, the user would expect them to continue; in this case, is's probably appropriate for some 'relatively permanent / long-lived' object (a 'background manager') to manage the activities. In the latter case, the VC's would interact with the background manager as appropriate.

So (as it should be) it comes down to what do you (and more importantly, what does the user) want/expect...

Upvotes: 4

jackslash
jackslash

Reputation: 8570

From the docs:

Once you add an operation to a queue, the operation is out of your hands. The queue takes over and handles the scheduling of that task.

Ideally you shouldn't modify your VC variables directly if it can be deallocated while the operation is running, but should compute a result and then do a callback. If you are using ARC you can keep a weak reference to your view controller and it will be safe to reference even if your VC gets deallocated.

If you're looking to implement concurrency you might want to look into using Grand Central Dispatch and blocks. This would work better as blocks encapsulate and retain as needed any variables you reference inside the block, are much easier to set up and execute and make cleaner code.

Upvotes: 1

gschandler
gschandler

Reputation: 3208

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.

Upvotes: 4

Related Questions