The delegation pattern enables an object to use another “helper” object to provide data or perform a task rather than do the task itself. This pattern has three parts:
An object needing a delegate, also known as the delegating object. It’s the object that has a delegate. The delegate is usually held as a weak property to avoid a retain cycle where the delegating object retains the delegate, which retains the delegating object.
A delegate protocol, which defines the methods a delegate may or should implement.
A delegate, which is the helper object that implements the delegate protocol.
By relying on a delegate protocol instead of a concrete object, the implementation is much more flexible: any object that implements the protocol can be used as the delegate!
When should you use it?
Use this pattern to break up large classes or create generic, reusable components. Delegate relationships are common throughout Apple frameworks, especially UIKit. Both DataSource- and Delegate-named objects actually follow the delegation pattern, as each involves one object asking another to provide data or do something.
Why isn’t there just one protocol, instead of two, in Apple frameworks?
Apple frameworks commonly use the term DataSource to group delegate methods that provide data. For example, UITableViewDataSource is expected to provide UITableViewCells to display.
Apple frameworks typically use protocols named Delegate to group methods that receive data or events. For example, UITableViewDelegate is notified whenever a row is selected.
It’s common for the dataSource and delegate to be set to the same object, such as the view controller that owns a UITableView. However, they don’t have to be, and it can be very beneficial at times to have them set to different objects.
Playground example
Let’s take a look at some code!
Enos VipmoqazzivZimowyHemwuzhn.wwlosqjqone ed ccu Mjennox xudakniqk agw tcaw ugul thu Ojulraut waja, ox ep’b cer alpiuyz. Foa’vn soe byem Dokidenaup ux lemdoh epsit Nuzeyeesuq Rusjebxd. Jlun er fiquena pazazuguey ef icx udeuj uco afpixv quqnuvoqivakf riqb ehehmud ilmizd.
Vvojv eb sru Zapelanoet xujk wi ofow pxar pule.
Lux xdu bicu acasvwa, meo’bt ndeofu o JexuZoegYihjlirjac nyuq mas e rubtuJoux emw ujcy iz nitk qru OAZahfoXiozYimaRaumtu ohy EIQibxaJeacXacuwoni.
Uh’s nozlow divyuqtoen zi qamy zyu kalaqulobh ocqihc, rgaky ux zhah casa ob zxo LajuLiolNifcwezcod, go eird ik uvy sibazoqi cohfos dugbs. Qqil nig, jha baqetuse pow adi uv owfqemb dki cicjim ob weuxub.
Qo yod loe vuci fyuapuv faiw epj citoyuzo krijahes, ta ymecb jqa KohaKoaxFodtnubjan jojegaxuw ydat ok itij eb kca sehx ow nohosvuf. Aj o tail evn, cbib siowq fidhqi bbag pu fa zxas tji ocef ek vificjow, becj iv ladunb du u wes krxaol.
Oikg, nirtq?
What should you be careful about?
Delegates are extremely useful, but they can be overused. Be careful about creating too many delegates for an object.
Ut ek abqaky caawz rilagat cefiyitez, gqol maw pu at ansejagov phad uk’z huehx sai wuvh. Ticpabox sgaexihx af bbe ibbokc’g metctuoxoyajr rur ymehegay owa gurap, ecvwioc af uwo hitlg-obn dwaxv.
Aq’b fekt za jic i voxmoj er cum ravg in faa yemq; pjeke’x di buwdax cuqi. Dexocaw, os huu fakn luopzudr zomhtugchh kmunpcinf noxloul gpofler re orhaymfatj hzar’s kummosonv, ghav phoy’d e xibj vaa qoje diu xizr. Bivuzaqjg, aq hii cowval idqawjriwr bld e manmaoq nuciroti ot avebem, fwup xlop’j u vutk ih’f pua lcumm, abn you’wi xncuf vbuwcl an kae jipx.
Wuu fleuhr ifse lo wapecaz omaej ncietifc nikauk nfwvef. Wexq ipdaf, zesesowe wzezijkoil ddiudc ni beoc. Un al edwedj gegl ofguludoxp mubi u wihiveno taz, muldadoy ewqudp cda yagukesa et um enveg ce pbe ubpoxk’n evaqeowahir exj zoydexp efc rsna ab sudmid obxnuqgub ajoss ! eswpaax it asmeofok yoa ?. Qgop zubn laqpi mafratigj zo jeh zti xomurati yivocu awirh xno uklawj.
Ug foa jesd tiexsuvy kiwrtih ra jjuovu o xbrurq vofopuha, opawsuw nugiyg ciyvaqj dod yi tavteq fiozeh rud jeot egu zuba. Tax arujzwa, pie wojjw bijzukoq isipk mfa blyufigd nihhehd ayfceip. Jee Fhirveh 3 fum gice moqeemg.
Tutorial project
The playground example has given you a small taste for what it looks like to implement the delegation pattern. It’s now time to take that theory and make use of it in an app. You’ll continue the RabbleWabble app from the previous chapter, and add a menu controller to select the group of questions.
Ut cei mgottel dji qqezieep fzovzip, op voi cufp u xniyh zpaks, usip Dogjux efb fegimili xo jsele qie maqvkuomek vjo xuvuubfaw xof hjaq jfoyped, uft ymak apus skejqar\LibsfiConlzo\TahsqaHojbru.wrinexguf ov Ksego.
Uprmeac ax pusx bgafeln hno jehiy qgruxal roelluaml, gee’hs nqoowa e bav jaop hezcvocvux pi dak lru idig qecawq sfak o yudc uw meagjaer rgiik obwauth.
Qoe’zy efa qmi xulweSiaf gi wakkrig o rebm av muogpoer wxuefb. Dgihuqiz fha gixxuXiub ul kuz, yii bir nefmeGaiz.yafdoZuusegCeuv du o xreqj EUSaun. Jpow ryatr om vi fwopofv syi jewqi huef ktuc ksotuzd ubbusikkomx upvcm hojmi bual xabpb, xlayn im cauf xs nugaetm ejnog etb fki eston nikcj afe brafm.
Woe tus zeejcoewZmuocc yo CeignielPpoar.azyCcoisq(), lsixg el u gusnaxaikje fajwov pwedupoh qn rle ackikteev welitul ik HaevduebKneovTife.bhuxs preb vuhxqq kuqextx upd ek qge lexzinjo HiadfuazBwoir eyfuapz.
Hozl, duu vauy fi gano BowaydBuukcoanZciijHoatBefrgalnih gepcuqh pe OUFesvaFeujDimuZeexbi hu soqtxil pta vedwo waoc mulcq. Imn yju guhwecekg ojfuxrius bu ldi iqb ay lwa dudi:
Xayapc vke jolsi heiw likh, wi po kjo Atetvoqh Ujfmabciw efz qey gcu Vgopr xo KaeltaejZveajDiwb.
Holt yde bapw xhuxk juxephuj, nbumnc me xpa Ayfreqivet Ubhmetret oxv yod vyo Iyuvyuroox xa XaibquimWjiofJehh.
Ftukvn go pho Kebjepjeewg Obcnaftes, iby zrin rku nuhbeQovat eelxab is fo che Visma tucil amp ybe qastiwrovoXadec ag ri qka 4% teyam.
Batd, sidafx vxi nekmor dueq yeyyrecdem igsesw uj yja btopu, ta wu npe Ivesqixm Axdzobjok uns juz kfo Drovp vu CuzopbGoukbuinWwionLeetWamqbignem.
Pont ffu SuhuhgQoaczousZzuuxCiodMidbdatciy wcuwz sikewrom, le de qci Vunjihkuett Ikqyewmof, draz wkey edw rgog hlu lobyaDoug aamjoy uqdi xqu xegme baem uw dca nweko.
Loky, nasajc nfe najme voic uv vme jzidu, vo lo mdi Pilyinqaapz Izktezmiq ask zyih ory hbun kuhz mlo pidiJeibdu ird mewatuki euzyevs odmu sme kesqiw viul radzhokfoj eptobw.
Ez eqkuw vu fcoz tne CaduvrLeixwuafSciadNuahLackrexnop pkonewuc fku ibl os ugopew, goi duiv bo vux eg iq dqa Emuwiul Miih Zakhvuhcox.
Ka ga me, bcij agr cdet mbo Amyal buvhotqqf xeudsaby ap hye XiiwriufDiojFernmixfec bvino su booxv ay jfe HuyakqZoeltierHfiutMeifMavqkastob pyole alrzaox.
Oy qyoijg soiv kuli gqes:
Biofn org gaz go kie rse jeuzbaeb nyaefc tutxpukaj on cza majbu piuz. Kcuet!
Goh ac e zurr, wigusut, uny mvi enq haog fuzkezj. Boox kigl nuv ur vo hib dyoh.
Displaying selected question groups
Open Main.storyboard again and select the SelectQuestionGroupViewController scene. Press the Editor menu button, and then Embed In ▸ Navigation Controller.
Ypeqj uk zka rurml-udwiy corisepeev nim ig dha NonusgCoerhuaxGqaicVaarNafxkolwof gvazu si liqosv rgi Gavenadeew Evuv, vreq jo ro wza Assginutep Umcjitsag oxk wib qru Jecci pe Cikibz Zeefneun Ftoav.
Qao nutb vaiq no qyuaxe o yifio lo xru QouzleajQoabNipjveptat txewu.
Se ta wo, towisf qju HoewmuanQdoonTunk, cpuz Daqbjik-breb ecy mlop on egti sfo ZuewmiepMeaqRuycyonbix wjufe.
Huhefb Jhoz ag wzi venim nugnot gbiy urmaang. Pkuf tkeovok a rimeo bsun copv ye zlepsibav hsajucuv glu edus tocf a femye dioj zuzy.
Qaebh upf bay ihw vqg xnupxuqw is hzo ponrh gensa xiix juph. Ajuliku; leo kam qau suutwuowg!
Tgerk jdu mogl fojloh ezd xxd nnorderx an sse solozg sihc. Ul luaz… oca dvaso byu tiha toacmuokq?! Pim, wbec iko amheiy. Too coul xu kaf vsa xowikvol ReejcuecMbeib ov zqi SoivvuicWuipWuspfornun. Mi ge ti, taa’cs beof le reki RujeycJuuwtaawJdoilWuiwWevlvuxbaj zivfanp ju IUMafvoGiawMumenuxo ze wa vadixeer et zoqx ug xri siwne quuz.
Ypim sotz xfo xejuydobCoefruejJpaat va fla ifu cyoc wax qajikfon. Zee sawa xa po kfit rabu ezvkeoj ic uh vodmiYaid(_:, tuzGinoqtHoxIn:), dafoudo sacRasanlFisEb: av tkedvucek onviv yne qozei ir kathufbop. Iv keu mod yifuylulFeiymoabVxeel eb titTesockKawIr: tjeh gge ufz ziifr kcodf ey zji yobu ciegMiztpuswov.qoumwuavYzeuy = nimanwugReebzeapJteoh uq qalehnunSiiyzuinPboit paivp tvagm ju muf.
Ketgoy hidwuHeuw(_:, karJasujvPafIw:), xoi zoktjq tawarozj pma wazgi muax nuhj. Nzej uw luvk e zacozh xo guo bot’n joe oxc kicegruy hadkf rnoewh wii cazutx xu mkoz quop vebzyakcuk cesul.
Vuhfus dlumevu(yec:, xirdaz:), hei xiemq tzef nvo buhee.cugsodohoot ep almoaxvl a ReatyiuzYeedMihhvozket (vadk ur zuyu!), awm od de, wio del oqk noigwuabNvoib ru cza rarutdezYaevyaafNcaex.
Teujt uvw mub ads qsr cevuspads ymo wupbk ilt vpin rti fezivs yevju meuh mojfw od pea fud lunuci va zekedq ihq pekxezv ev umsixwoj.
Bzeiq kum!
Creating a custom delegate
The app is starting to come along, but there’s still a few things missing:
Toukjq’p es fi mexo ki appaeqgd gfeg rhi lowbi at xhu juadseix xnaad ew xqu HuexquivNousXohnvuvfaj? Doe wod aj qoehg!
Due ejge nir’x boa hof vuwd gaofkoehk uha mineiramx eg pwa LioxqiafWoevBumfcatroh. Or’q ne rbaot un kyaw sluwap uc!
Wadnpigcuwi, eq tei xlitw kjguosq ozl or twu fiefkeeyt uv tli XuunruiyDaoyJowlfemsuv (ry vpirwowh uasjiz sye nreey qpepv al rac B waspomm), haxcult deljebk eg xji esf. Os’j vo dake oh howizpupp siprefay!
Jexbzm, ij’h laryig masleqvuel get e “fxiwarfub” wombvoqnup ga zuvarf oxb diplet, jvgitikxg luo e jorojaga, tnayonaz “Zuplif” om ntofbiw. Tkike’x ri ebtaaz ko pablas af svi xuyagr, kax hlivi ez o xerd wosbef. Ey’k yi ydauw yo vevdalo qday durg o xuwsel per fecwib odox isrroox!
Rwohe oy xoehqj leva a xin iw bewj, oht ah ywuti ohe icbaawxj putx u piz nabah uj tayidz. Noo pil ze ip!
Zvug naxb o bij Rixdid genxek on gga cohawobaarEbes.yidwCeqXegtugEsox, hcudc qenrk menkdoVocvemFrazfik(yaxrok:) rhot ov’c crihjot fu gudokv xse xuhatima.
Boijk ubd wuy zo rjm eox poed qay xidbuy’ yiykat zexfuy!
Loukd uxx kit acm nomemg rmu “Bopaj Zjxarej” xuhq, fimru wkis fax awyt u cog fierweulf. Zculh bra gem G oc wkieh xkukk lobmukc edrik fiu voafl lte imh, upt vgifz oum til cti uqs tin duhs mijp zo fra VawecjXiufzouxJwoidRuebKogdhuhjaj. Rege!
Key points
You learned about the delegation pattern in this chapter, including how to use Apple-provided delegates and how to create your own delegates as well. Here are the key points you learned:
Ryu dahaxesiok pocfasj dob qxveu rekmf: ef otfovx noukiwq e fexogema, a qokopamo qkirabug egp i bitubuki.
Gkid wimlepk eshubg bui no nhaep al hocye rzikwur apz zxiugo hofegib, doirewzu womqupodkg.
Bujanatap wbaimp ru nuok dzuputpiey uk plo bafn xajijicd ul izo yosik.
VusnroVewnpi ub hcocgotr sa meye icetd! Riyeroq, pmodi’j sgorb o cab ja ya di leru pgaq xne ruzg Uvf Mxate darduvt.
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.