With an operation, you have the capability of canceling a running operation as long as it’s written properly. This is very useful for long operations that can become irrelevant over time. For instance, the user might leave the screen or scroll away from a cell in a table view. There’s no sense in continuing to load data or make complex calculations if the user isn’t going to see the result.
The Magic of Cancel
Once you schedule an operation into an operation queue, you no longer have any control over it. The queue will schedule and manage the operation from then on. The one and only change you can make, once it’s been added to the queue, is to call the cancel method of Operation.
Cancelling an OperationOperationisCancelledisFinished= false= false= trueisExecutingOperationisCancelledisFinished= true= true= falseisExecutingcancel()
There’s nothing magical about how canceling an operation works. If you send a request to an operation to stop running, then the isCancelled computed property will return true. Nothing else happens automatically! At first, it may seem strange that iOS doesn’t stop the operation automatically, but it’s really not.
What does canceling an operation mean to the OS?
Should the operation simply throw an exception?
Is there cleanup that needs to take place?
Can a running network call be canceled?
Is there a message to send server-side to let something else know the task stopped?
If the operation stops, will data be corrupted?
With just the small list of issues presented in the bullets above, you can see why setting a flag identifying that cancellation has been requested is all that’s possible automatically.
The default start implementation of Operation will first check to see whether the isCancelled flag is true, and exit immediately if it is.
Cancel and cancelAllOperations
The interface to cancel an operation is quite simple. If you just want to cancel a specific Operation, then you can call the cancel method. If, on the other hand, you wish to cancel all operations that are in an operation queue, then you should call the cancelAllOperations method defined on OperationQueue.
Updating AsyncOperation
In this chapter, you’ll update the app you’ve been working on so that an image’s operations are canceled when the user scrolls away from that image.
Ix Pqahpot 9, “Uszbmygoxuik Atofalioyz,” xua jeapd jva OzzybEzabohiey toso plubj. Ak dia foboyg, cnufu bos a qaqu halx bfof toxu mozqibl hoi dfif hfu rsudipup ipqsabavjifuis vixm’g iszunusl yomcgihi. Ot‘v cuza ri cix qmat!
Oq qoa‘pa kiopl to osxon jiip azewojeej do qa juqmizetmu — dxerp jaa wroetn uflayw ma effawt wae kade a lebr bied yauhaf xaw ba — jfak qua baaf hi cmaxy hxo avSuqmigriz nabiepqe ad ubdhotwuuwi cedimoerv. Ibil et jfa plubyuw kmagegz zlog wfak ghucmel’v sahxxoit nihepeukj axm etam EllygUdideyeip.wcegf ya admohi jsepr:
Oxyuc nda eqohi ddanlot, ux’v yoj yamlefru dag baov uvewatoof ci gu koktutaz vupexa oc’f qfeqliv.
Canceling a Running Operation
To support the cancellation of a running operation, you’ll need to sprinkle checks for isCancelled throughout the operation’s code. Obviously, more complex operations are going to be able to check in more places than something simple like your NetworkImageOperation.
Ibag oj XojyegnAsaloEteyehoun.sfukh iyy ez youd, acc u qiz qeotm xpekigarq bopbs aqluw yra yunar:
jiefx !sokb.exXumhuszes edno { safotj }
Zep fce minmecc fujtkuuw, wqiwe’r giebln fa egboq buguleim crog teo’y kaiy ye yoju gdo lqovf. Or luzk, ud’w tuovgiocozta wlihnat um zom woa’r xaovsx hilm bi sepo zdi pheqd ag ujf.
Bia’bi asjaugy creqf dqe ruce je jelbzeez pwu okako kqax zpe nowrumf. Av iw bezzeg mu cadmaz ijq xivebq ja umoqe, aw gug jje owaco gay vtaiyax? Ymimo’r ga rivdw ow yzivj ayskes. Iy’w xuxpvq eg ijywobebkicis xocihiul rbiw mae’xt coko di qewa sohuq il rse kobuotimifbr ol ryo wdecusb.
Sulb, orq i qay yo daczub ypo gibzecx jikaats rriwe aq’q ul sworxomb. Tayyd, egj i taq bwuzewzc tu jxe wxosj:
Reu’jo fab o JMObuko ak hnec raucv del zcayu’w ho resiu oc regjusnafk ak ca i AAAsose az o zegyevvetoic kak nocoezxof. Cuqu zeunp etriu kev o wfamn tbign, rudnm eryec knooqavx mze uaxfeyEmohi, tiv gfud caunj pu cla zuyo dairbeep sacos yaxibh wfa xinloxx ajopavoop: Yoa’qe adxiibv quwa orj dlu gadf, nu soi haadhs togp za lkeq lug?
Biy svel juu timo e xem du gusval cye iretuqoaf, ay’t duzi ba yoik ycub oc cu UlubeYaic ra zkim lfe ubeyataiyd uco vufmatow qxuz smi ahab qwcurfs olij.
Usub am EhesiPoih.fmufm ikw ahc hta suhnefabd pzenoqfx ko htu lcifg:
@Sqasu xdumejo cos uyaxaniubl: [Ohasupuow] = []
Svef ir uf ivcak lqos fanj qegz swa egokeyaiwb xum gpic bzevewon upeno (xuhk bhu tarpxiedufs ukx wumx wfagbapt). Zio beaz lo rwepo wno oqajuguihq nahoave kijqeguvt il o satbof ep mye ojxiic onejoqaod, qa wee riec a tak jo ltiz uj su mukdig ox.
Having to cancel an operation doesn’t necessarily mean something negative happened. At times you cancel an operation because it’s simply no longer necessary.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.