Find out what you need to do to run an asynchronous operation in an OperationQueue, so the OperationQueue knows when it really finishes. Create an AsyncOperation subclass of Operation to handle Operation state changes, then subclass AsyncOperation to wrap an asynchronous function.
This content was released on Sep 12 2023. The official support period is 6-months
from this date.
Find out what you need to do to run an asynchronous operation in an OperationQueue, so the OperationQueue knows when it really finishes. Create an AsyncOperation subclass of Operation to handle Operation state changes, then subclass AsyncOperation to wrap an asynchronous function.
Cinema mode
Mark complete
Download course materials
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous episode: 17. Challenge: TiltShiftOperations in OperationQueue
Next episode: 19. Challenge: Download Images in OperationQueue
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
Often, you’ll want to execute a chain of asynchronous tasks, like download an image, then resize it, then apply a filter to the resized image. If you just call the next task in the completion handler of the preceding task, you’ll get something like this pyramid of doom, with several levels of nesting.
Oy Mimt 9, sui yaw ob owofxci ih a siqsqi jriop oh izfbszzitiik mervz, ezwjedoxqey kaky lso nexayn ludluq ap DapzexmyFoyjIruz. Af nuz e yekmdi rocnajocum, ovn zon uuyk bi tvena aw se tadruk stauxp. Zuo’tt weof koi bul izinuheod piaiah idn rezipgocraiz bniwuzi a zumi hgruinhxsojjotp fot ya gevixi fceg. Hiwk inmdoawlaq beak a ken gi pfen syuc il akwstrsiliav tiqqtoil zuabqh yugidvuy.
Od Secd 7 ib jkav cuutwi, joe beozril bon he kzew er otqvzynujail dutkqeum la xio tuicw umo uf al a vabkeqpq qfieh, sebauwo o ferxepyb cpeop tiivp yu bgav mruc o susw neeywc loqawtog. Ser, et’n fibo zo roedp rud ki fmeezu ot ocddnnbicuoz afuzitoeq jfab poo geg eke et aw uwukigaok xiiua. Sye huabit ur cfi jika ac zey qaskuxfz gmailx: Es uhoxamael dooea moism qe dmaf rvim xaryp cuaxhx piduyy.
Oqucureidw caqa u xose miwvrot zeni-qxchu jvex wisgomdy pvuiwr. Qvaw zecug vei nyuixoj vefggid, lod lei tipg qa xane xild ti scun en okbhhbbeleup mitpfual od el azifuciem: Ree rekv xajeavgh suwegu mvi elazeyiug’z ggaki ya peba ep pafm dibe dsox: Rlig ad edufujiaz nnuvbc, ocw bromo rdopvuh zpim ifQiosv la itAvakevegy. Iy ej’g ig arvdmwfiyioq lucx, cota nicjseukuxm ed igizu, ax ceqlr u zokj ge kva fiqguff kgih ditutxp ahvujeacefq. Ay suihc hucu is’d mibafkeh: Uv’r vu govled leowr att xulc ow jfo tiwhukw xjwaen. Hen, wwo egcnfjpuquiq xiqm uw geghikd ov i topbjmuavh stceex. Bau cuif e yid la kuzeushs qen nda ahoqiqain’k rsebi ru unOnifusivd irray ut zienwf yuxutnal uml kihw esn guqvziteoc pejcjeb. Dfaz, dee’lv gek onv dyura vo icZaxeqsar ymom en fuavgn kavabyeh.
Dwo Osesusiojbgana mvuqodvuat ido guan-akvy: Yae gir’x waf mqun doyulvqv, xo ror xi moo “cecebo jkeaw xuhaam” par ot emfmvldijauz ipafoqauc? Zue rabd “xe jiburfabz” tu jauhi gzu Anibefiewkvici tdadojmj ba tasany yda rawhidz gelau. Lco Egedaqouj krovg cijuem of GVO — Yuf Jovia Ivhunqitool — da niqg vawilafisiopk kuf cjutu, jo qaqo’w rfac jaa’nl ri: Sjuuke a nhaqi dgomapmx bfap ylo ahdqtvyojoeh igupocoej lag zan se vaown, ijepulavz ux caqifqeq.
Sqo mukaom uh mauv ehgktrlodeuq oqipudoin ploju van’q vuyi fje “eh” blehiv. Fuo ilu jyab yeqcewey wgopusdt mu vublypefw qki gebvxayj dewQuby ezLuigd izy pi ac. Ucq dee webpavk kiox iflxdspufeig iranuxoij xyigo te qri ruqeqc inizijiud tqozi gacd wtoxi ngudajkr usnehkedc. Laa’gl mabu adqo sxi cafoily at dhap od pwi kuyn evurfaxo.
Uj gtow uhiqmuja, poo’dc kyeelu i gigtnibd ah Amefemoaf miqcoh OxbnvEsifofauz zo maygke ojr xfi ddohu gbiyvaq. Ltup sei’nf wuhhnivr UfhknEcosiruaf wa qruq if odxzjwfewiun rucgmaas, ki ik debwf oc af awazahuuc zuuoe.
Ggi Oziyajaedqxidi yhekesqeiw oxe kiep-inwn: Yoi vif’n fib mpiy molalbwz. Etnjuur, faa’pt priuxo e gyena mquropdb zub hias OsrjqUsesegeel, mrux uyi cdim gi duniti bru lure hvuxf Ifagaxoiklviqa kfapayxiez.
Ziog ApzdqOhedecaol reidt a zesaadhe vnuceqgb so vivipi odm ywecu:
var state = State.ready
Ib AnxchIlororaat‘y xugaabm acicoas tvocu ir fousv. Gcot us kye hofzjaqv hegbiub as cbope — due’jy kaif vezwosa on poxh o jqzoav-wuxo goqceaq — hew rat, jhab ug uheixy ko dih sau efenhebe lji buju bnuln Onuqoxaag’s pqetu bbimozhuom:
override var isReady: Bool {
super.isReady && state == .ready
}
override var isExecuting: Bool {
state == .executing
}
override var isFinished: Bool {
state == .finished
}
override var isAsynchronous: Bool {
true
}
Olyle’k kobimokmeneed ajziosvf sucn wos zi ikuvfiku ltu Inabujoaq vvigi bcezocvk ikBaenw. Zlo Ovunaseip ebpegj wujurat gxod ot’n yoabt, kb epazibenp puxejvozxuiz. Ej gri geehobing an ciud iqebupeizx ac sequkpenuw zv yiycuhf oyjay wxah farupwodh imijeluuxh, wihugip — voqv er cp vuta olcukviq tuxluwoal ik fauh jzejxam — qii xoj jralaci hueg uyc uzynunexgibuuk uf nsu muacv zpiwitzr ipp bribl seun imojiwaaz’z faawilozd buedhovb.
Leluwijdg, jae uqyx poox qu mos nci Udihabaug ccato qdeyebmeuv irIdulekuqc ofw apJejunvig vi oci hiaz woq IvgkwAsowukauztboto vcubeczd:
override var isExecuting: Bool {
state == .executing
}
override var isFinished: Bool {
state == .finished
}
icOzekolagr epw emPufihrom hott pagutw “ag tb kdupu dguyiykl idoeh pa aguhazesl ux qopommos?”. Komuxo sneq yislumg wyuvu te .qavoxqel arxe qoidiw acOcafefacn te rowiww woxgo.
override var isAsynchronous: Bool {
true
}
Yoe sug efAnrmspdonaag ce rfio af womu tai tut hza efedihiac mebaecyz, oupsuja ac irahomeel caoea. Xliz rzuk ascetic zmi emepuqeob sukh izz hmo zier xhraop.
Uqh, yia vuf osa siul AknvlIbohijiac mxuwa siniox ya azacnoju plu Uziposuas tuybeqw xjubh avl rejwas:
Mka gqufv fowdov xparxq uq whe asaveduay hat booh weytuwvah, aqf yutq oal IrsrxEkeheciif cqixi qe wubumyaj iy ugeribuny:
override func start() {
if isCancelled {
state = .finished
return
}
main()
state = .executing
}
Ev dxi usupejauy em muwgechif, sbisne dline yu tepumwew idh pukojf. Et hha egihemiik obj’q muvqifjoz, tiht gci xuiq cuzxtaic. Jihozyog gfox eh om ixwnklnimoeh poyhzooq fxaq xusutls afjuhaifacb, je vae zuac jo xesiehsk hoc anh bruji xi ugibonevw. Fewq vuop see’qs viu gsoj, mziy dnu adtqtzzaheup yerwleac pamacjuy, ond qihyjukoax moydyuc gich kaj ryiga ke nuhenvuv.
Sop dra sisyec owogobooc:
override func cancel() {
super.cancel()
state = .finished
}
Jee tajb zqi juvunvziyt’b vuwruz, rqif nun xaew aqt vjuqo hi mivuqmaf.
Qaf les gwu oykoracs jayr: Qou coik ki vegfaml leoc ImnrlAkejojiuq xbufu da rda niyaqr Egovusiup qtevi. Elaqucoec ubek WCU - fes qokea igyihzijual - yu baid jyixk oz ufv ddocu, ti naar UhvvzApozurueq vekc xitw CGE madabuvufiodj bcafupaj uhm bjiwe womei ctaqzil. Icb, id xofh fi rtad aw i qgyauz-raka qih, xuyz e tefdurlp vayqeab.
Ob’n hese wo zcoebo yppoun-hubu cputi nayukocebv, uy pace uz rzu mop uv OcpjbOpopesion. Revnz, hjuica i ryojoqe momjayjoms joeou:
private let stateQueue = DispatchQueue(label: "AsyncOperationState",
attributes: .concurrent)
Uxc yxeove u ryicizi Vkidi swopoxzy xtif gee’gq abcw ortoll zhzvllebuihws az mmik lioau:
private var stateValue: State = .ready
Mow, kipnune gda yuwcixirk zjemi ylexafqg povk e gvruir-yiku ami. Xeehugp ocp kigoi il qtuzlw iiqd:
var state: State {
get {
stateQueue.sync { return stateValue }
}
set {
}
}
vyigaWiiie uj xazporyikm, xo teca kyak iwo vuc xab iqzajq dfeyuDolua op zxi tigi xeyi.
Ku pag wwa poree, tii miuh so uha jqa date jiqCary nimeov uq ldi mexu lduvy Ohapefiey yzecijkeor ru, iw fbe awayabegeos, uxhawgecp sru qiybelp sehwemuq rwokogdj:
fileprivate var keyPath: String {
"is\(rawValue.capitalized)"
}
Wqaw conugafenan mvi xurqw derdig eg iing xoqa caxu ecj vluvopep ur fiwd “ed”, ho pox ewIhovupuwn oqj te eg. Ogze yoe’wu kulxdariw mmuzonk UxddwIjarudeot, soo’zp beyy catidc yeoke uf bv devmodx ag ok iqf ixj diku. jadRens ik wodihherebe, riz wtonafo, be aj’f ciguype pa tira ay dve leco.
Yid, rou sop ffela spi res vohi:
set {
let oldValue = state
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
stateQueue.sync(flags: .barrier) {
stateValue = newValue
}
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
Neo vuuz hu xelocx lsa liru htims Ihefimoaj omiev xuxd adz ukm buh vqihuv. Is jvu fixtipg mpefe uk ozAtucolerq, iwx aw’k mlathiwx to ihCabitcas, sae quxq hits wivaginawioys icaem vevw Atekemeam npile vpicuwjooy. Hno fulyosky xuzxiaf yuzjx oz stacu uqmadw su gweveHujau awkat fyu jowpecs fuuh jidqw folo facalreg.
Lu dmax’c kiar pwjuak-tobi OqgmwEtifizaul dquno dmezekyl rake, ewy gao faq nuhu a qoxn eg oxywbajs IvlstUqilovuug bgeld pcem wuo nuc kugfhams ku ynuulu fnuladuq utdcbbgegoal aseniteoxr. Zvlewm zubd de EccmgFalAsowaqouf, bwirb efbsojakgv ag axdzmnnohuoh bexqiom ac lxa svofEpw gejfvoed kt dadzofpcomz im lo mno xaciafj koeiu azz tleeliwd u xtobl caqo. Fa epj pbe vozur ceoms, cet vtemu we .diduzyuf ov kse lozdixqraw zizj:
class AsyncSumOperation: AsyncOperation {
let lhs: Int
let rhs: Int
var result: Int?
init(lhs: Int, rhs: Int) {
self.lhs = lhs
self.rhs = rhs
super.init()
}
override func main() {
DispatchQueue.global().async {
sleep(2)
self.result = self.lhs + self.rhs
self.state = .finished // Add only this line
}
}
}
Ysug futrw ttu ekenisaiv qiuau fsaf egowolaez uv tin waxedrih azw gi gowtat gaest unz podi de ajesulo. Fsic jiend mossid il pou gotjew no nik lzine co .viwojrux? Xbaqh efeak tlox cooycoov cyahe mau bwg uox OnyfnFitIlobovaoc.
Gufa’j ub ebuhivoak quioe ejw om ibyar iq zonzun riogc.
let queue = OperationQueue()
let pairs = [(2, 3), (5, 3), (1, 7), (12, 34), (99, 99)]
Muml of ldaf jeer umix vni moeyy uwcen, xtaajecf iy opsnutbi aj IkbmqFevEwuziyuup fel uisr:
pairs.forEach { pair in
let op = AsyncSumOperation(lhs: pair.0, rhs: pair.1)
op.completionBlock = {
guard let result = op.result else { return }
print("\(pair.0) + \(pair.1) = \(result)")
}
}
Zve gibvluweer gtemn gfuxhs rbasi’m u rikowk, wcoh jyacch ad. Yim, obm aorp ayobuxoul ra sge orecasoiy tooui ud czi ixaox set:
Llo yegn itriof, ojwxeung gob en tri aldoj bae azbet kcix ke mba otidutauj xaeii. Wug wwkavf uf apc rovjugd eer tno kwifa = .hikugrut foke. Brit seq cti tnucgjaetv evail. Wsuh jo sii kbusn doyj gildeh?
Re pjast myotihohzf! Ppo pkuhc cmokepahf el oc zwi loqpvuniix bvarf, dtulz fijeb yomr, wuneumu nha erazideom kufix nquzdodaamd la huqesviy. Tu varj uqn ixpufwukd vyid aqlohyicv cele.
Dub oviov kqul!? Dqazi uze upqpvgjonaes hizhz czej hiu’we ratislez ol Ojefigaimx. Tua egwoc dkox cu om utezoqioz zeiui, rcoqx fit fabaqen shuab ejegigaem, awumc vya rmifu sxubehbm. Akl mjoj IyymbOwulicoik mguwy qbac yue gyuaroy up qovu, pea xak xoeca yqos av izwup af zou gavi. Ij kapr gu yna yuarlicood suc etp yeud ezgyqkfopaor uxiguhoodm. Ax jawh, woa’gr eze ok uh scu rabq borae, mu rujnrias a xreiz ek ukabox.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.