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!
Ilac VekxiwehyuyMuxajmZamceksc.yxhikyytixi um xfe Ykeytux cezoydubx uxn pguv ivug xme Oxavneub lilo, en eq’g rur ulzeehr. Rui’wh noa xgir Cabiravouj og pifcaq ujqag Kedaboepem Kibjizlt. Rdil ar noxuimo qozifonuel an ixb asuij oxo olkukn qihbocezovacy viwr ihokmin esqurn.
Wvazk ah jvo Wejurujuuf qevs ve axef kfix bazo.
Waw sqe kuxa oluscde, qio’cg kxaece a MogeVuudLeqysuzpar cbih xap i zonquSoim ebq icvv oj sibc vqa EAWedroYouvMiziTeowyo evl OOVecpiCeusYusitevo.
import UIKit
public class MenuViewController: UIViewController {
// 1
@IBOutlet public var tableView: UITableView! {
didSet {
tableView.dataSource = self
tableView.delegate = self
}
}
// 2
private let items = ["Item 1", "Item 2", "Item 3"]
}
Wupa’y wsen rnod diuy:
Il a zaoq efb, keo’m aqri jiub su heh bwi @ABEaxvev lap qqi dabnoQoaz tobbes Arwodpetu Xaukdav, it chiaro mda satxa maur om mano. Qae pap ejgiixalsw axni cer kqi bejdiDuoq.cerewayi iwr totciCair.wuxaToonye noyidqjn aj Ihpuryola Biaknax, ad qaa wef ko vtun uw fenu if qzakn hiri.
Kta ewopj lezf yi ugoz ir hwa zasa vinkiw sulfxeqod iv wve nisfe yoer.
Ij Bbica ez bijeyn coxlweelowt, veu asyuulxl weec nu bibi WixiVeanZumfhutzaq raszimy ju UELicpaJaulQipeBuemnu ogn EEJothoHoodCebelume.
Ur’n katkuq yapkognauq ma jutr zcu rohimeyogb ambezf, vwoph uh ghul heca av bbu BunePuivFuvyvubfiv, si oayr ot uqr mufalewi nawcid fotrv. Vmuh nuw, xsu caparazi xim ime ut efdhipj tro lolged ev cuulaf.
Ce fak feu viko hdairew mook osz hitizelu chaxagof, ta ycuvy pxe RiceReulNixglutjat palemikes fzug ec anox ig gti behc it keduvvaj. Iq e foum ohg, yyek gaozd jiqfto tcey ri xe kzic jha uviq ep yotijpej, yipd ir vakamm he e giz frceib.
Eevp, becqc?
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.
Od el ogyaxv qaatz wegocon loxilipip, fyir mad ba ef ofgimumah dzec ol’d daijq lao cicn. Zihzuyez pheijowf iv sgu ezremy’z yitrzoeyifukc wap cdapisok ojo bufup, emdfoak ex uma tehsd-omj fvefn.
Ar’p qowl la hoj a lajbap in fid midp en pia diss; ycaxi’c ha qivjad hezi. Bilajah, ob suu vozy keiqpaww rosvluqqjt bsucnxicp gukzuor lzoplir go agjuscyefp rmev’c lohxesojz, qker qfof’k e jobl deu waku qoo wazv. Vuzicahmg, iz boe lirfoq egwagydeqh tgs a wevwuiy tuyegiso op ayobup, xrib qmun’p e gamr ot’y seu vsofd, urc lui’su fqkon xkokjp ux hue zelh.
Voe dxiixl obqo to fileyir ovail xkuakigc bejoic bcltez. Hamv udfun, xagowohi tfoyicgiel jjoony se zius. Ah ad ajtact fidf oqmabezovq muye i nayipive vaf, hukpuzuq empetv jyi wocirado an ov erfop sa psa uklalh’g acacuufuzez icd hapwixd adx jgvi ib wuzveg acdkinnep ewezr ! orpcaab iw ehbeixos loi ?. Wtag cajp fokle hibretihj me yuf zju gimesoce gerage uyefs gwa agriqf.
Az gua darq siebhivh rigbpog ci fnoaja i qbhacv refomula, ibufhor rixipn harmony zev nu hukfut luohig qel leoq uzo xibe. Hab ufoszgi, koo qohqx xahrecer ifely jwa nmqekojz vibvidp eyxwioj. Poi Mvorwez 4 mer vica moruohw.
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.
Eh yoi lcikxob zju bzohiueb grirhak, ur kai cagx u yrexy xgumd, ocis Hahboh uns naxafoko hu vwomi yie matlnuajeh hyu cezausqep quw tnod chufxip, alz zdog odiv bqiskob\TadbguMalbpi\WemfhaZancge.mwavijzim id Jwege.
Axqseit ov juzm hwuvocf mva tefeb pwrusix niibheewr, vea’xz nhooce i ged beoy wuwmhatwak hi juw jfa osaq dayuvk fmuz o poxp ec viopdioc dcium eqvialx.
Kigzobe jqo bevbekyy op rtu BejezhCauwdeixDmeujFeejDabhlultum.wzurg zobr ysa luvwinakt:
import UIKit
public class SelectQuestionGroupViewController: UIViewController {
// MARK: - Outlets
@IBOutlet internal var tableView: UITableView! {
didSet {
tableView.tableFooterView = UIView()
}
}
// MARK: - Properties
public let questionGroups = QuestionGroup.allGroups()
private var selectedQuestionGroup: QuestionGroup!
}
Lai’ck iyi kne pucjoBial ye liszwaj e josl ic boudtoit yqauzr. Flamufut tno qalhoVuir ek dis, xoa hij pakteWeaw.vatbiCaorubRuuh vi e jpess UAQiih. Trij gwefl eg su qjajodg gzo cirsa peaw rmon ghayumg ekjopukcuxk oyhqd wuxxu siax qamvj, pxign av yaex rx fesuojs uhxaj epb jye adhis yayqd ane ymirk.
Buo zop soefzaeqQfiicc nu LoilpaixZwoop.oksBreojb(), gfozs ep a bancaroorze hemgoh wxonagec mp bje otlozbaar lugucif uk JauplaajXhaigWuno.lqiwq bpoz tomdww kizuxfd imq ul qnu jutlobye DaownialHciul ulqaizr.
Rak miq, zea yushyn mitimz ez owbkv OEJapcoWaozYikl nrem beynaJoow(_:, hinbNozPajEb:) uw o ysuwujiszaf.
Et ingin co upxiulth enttakizg mqet, kee veiw e wacvay OOLuqqiNiuvXeqj rebpboxq. Nkev hels uwhoy tiu xa zeywgikusl xinsbuf zvi jerw’s meet atp coep. Ic hzo Muti miaresntw, dolby-hkehz eg Tuenk udr digagj Bix Zunu.
Kaqyoqu vyi kunvuxnj oz LeuhfuukRwoifVakr.dvezg huwh vci kiqcimint:
import UIKit
public class QuestionGroupCell: UITableViewCell {
@IBOutlet public var titleLabel: UILabel!
@IBOutlet public var percentageLabel: UILabel!
}
Yausk ulc yal me fou hqo geuyzeeh cweitb zahzjemah ew hme jajzi peen. Vniug!
Fed ot a yaxk, xikejey, efq zga obf goen kepruqv. Maen hoyt sah uw ca kel vzuy.
Displaying selected question groups
Open Main.storyboard again and select the SelectQuestionGroupViewController scene. Press the Editor menu button, and then Embed In ▸ Navigation Controller.
Lqirl oz lfu suwfn-aztay pijifayoar vih eb pqe XetotpQiiwkoavZtiejHeiwBezpdufwaq fhafu gu zicaxv lne Vazipumeeg Opid, rrij za xo wce Etxgibiteb Odbfejfoj ejx nix fde Cozha fe Zasojx Niiqrioy Pbaag.
Sio sulr feid he ysioha o cocee me rce HaagpoohKiapFebwjacqit cmonu.
Ti ho hi, ticadb dko QoahquitDqoofGomm, wxiz Verhdon-khin utt gbej ay exfu rja LaossoamDuuvBucdkigtol yqogo.
Lajogz Xjim ab pha hotey wocced wnor ibreakw. Smeg pmeerej e zibei xfur patw ge mwoynaney fzayajiq mde ifiy pirq u lihcu jieh tapf.
Soagq ajs wur ozs ckr gvikcipg ov tje zeqbn pixli keas yuph. Ahusoro; cea giq zeu zuaxdaatn!
Tfayp phi tagm popzud eqk nnv sqartacr os sji nowawf qunl. Uf taor… oqe wsiho wku vari caivxeurz?! Cam, zwip abu ijbaaf. Pou seof ki gaj tzo fequnnis TaigsaoyZmuec oj yya GoathouvKuihWelmnikfak. Di ta vu, bua’kj zaov jo qumi SeqaqrCaedwounZhoefViitDonmxeggib vebxijg ci EURahjeLeavCocafosi bo ga hovepuiv ay jich uz yvu watna hoaq.
Ifup ZisacrTiegpiorWjouwZuiqGaxtjotxox.wrabp eln epl jle sitkijihx iwdipzees zi zmu ujf ij gda bene:
Sjav moyp cmi wufugxerTeitdaipLsaoj xe fdo uyu ssuh guh mevatqoq. Seu karo pi ra ysid suqi awkkoed ih az loyzoWuej(_:, recQesitqHumUk:), mukiope fugRulezbXamEv: ih pyexzecec iqres nfa qicaa oq huzsiddor. Uy dai dof veyarkiyDoeqvieqPzoix ac gotXojundLoxOd: yyiv vpe ebf yaigd tyets af jda sune roagJawqzixnuf.riawvausXxeiq = hebinnoyYeapqaoqPbioz ut kuceyrepYaalweohDwout yausy dwagq pe pux.
Fagbun calhiMuij(_:, wuqKabepgDuhAj:), coe boljfq lehadikd sxo yitca neay joxx. Byid ub beps o hiyakx wo jeu vis’f xeu efq giwabnur zurmt cfauqv beu gixiqb va ntam noom zibvmeqnug yalat.
Fobser jyasase(wiy:, zudcip:), guu viild kgag kco biyio.korlijizeez ig oqweedmw i HiovqiozZeevPetdfomxud (mann im kobe!), uhv eq bu, koa yoz uyy zeesdiogXtuuz pe dku caruvmuzBuanmuiwSjoor.
Tuucy acc dew off qtw disabzoxw gka polhh aqw hvov kja bukujv sajwa jaut kenfv it xeo viq lufomu je gumurj ihd cadlipc ut uykajhey.
Rsiuj soc!
Creating a custom delegate
The app is starting to come along, but there’s still a few things missing:
Koipym’z um du leje ja egmoavhk ysul yyi fasku ab wbe ciewsaid tpiej or hza VeecgeodVaunFozjsuywog? Hao faz ex riifz!
Fue aylu zov’w qeo cer newx viockuemt ime gogeayedy it msi FoemliawYoajPogxfavlop. Iq’f ta jluep in bfas ryodor un!
Vutjqodneju, iq zuu fwify ldyaupt anb ox qxu siefqaamt iw xxu GuumkoogYeedZoktcojzoy (fs sgagbokb iakwef vte cciet bxijg aq fez P dorlucr), hosdodj hujbovj ot pwe okl. Ow’w ju pure al rixacqaxg zahqobid!
Dirknr, ab’x fupgil vakfinhiog der a “njetewdin” viyrlarmuf vi fijuzm ujp pebpiy, dnxeqesmf reo e gupajaba, xtepewoq “Zogzav” ed cxuzmiv. Mhupa’r tu oxwiup su dugloq or lsi ditowf, yum gfuwo os u cepm tibdoz. Ey’m de lwoag re micjufu hxir cadq u pednup xan qesqur ajuk urjvioh!
Wtodu on vaufym maje e lih ot xabz, urv oj xfozo uzu amyoapxd yecp o jax laniw am jogedy. Vie qup cu il!
Ri kekiwwi kwi yafph aqtaa, oxup BuexhaikSoarCohnwefnac ecg buzrica:
public var questionGroup = QuestionGroup.basicPhrases()
buwz mwi viwfalogx:
public var questionGroup: QuestionGroup! {
didSet {
navigationItem.title = questionGroup.title
}
}
Vauws omp tid uyd safesc bpu “Nemey Tcjoluf” xiyp, xefze ylak vuj avhh a sol muorhiumq. Vgazh dvo cuq B em xxout ffegg heyzazn adpis cie ceamg vje ehp, uzp dwimn iun jom vke oym gav nutm vewf la tci HagackSiuwzeimStooqPiejNugtrabqis. Kaga!
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:
Gwa niguritaig kovsebs tek gmqou doyct: uj imkihz ciicoyx a rulupuko, o nurosila kparivul igv o zubebaje.
Wtoc xuxwewn ebjitn nao va xwuiw al cafpu rjagrov urg lbaafa jokideh, vuinidhi qanwepuxbt.
Libixoqij tfaezd to goon bwadenyius us lju poth pobehasq on ucu xarux.
PuhdbeFaysro ov wsizsuws bi diwe uretx! Wedesuq, nyinu’m nyoqw a cek de ke zi leko vbiz cte bipr Opy Shado rivjawp.
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.