In the previous chapter, you created a table view for Checklists, got it to display rows of items, and added the ability to mark items as completed (or not completed). However, this was all done using hardcoded, fake data. This would not do for a real to-do app since your users want to store their own custom to-do items.
In order to store, manage, and display to-do information efficiently, you need a data model that allows you to store (and access) to-do information easily. And that’s what you’re going to do in this chapter.
This chapter covers the following:
Model-View-Controller: A quick explanation of the MVC fundamentals that are central to iOS programming.
The data model: Creating a data model to hold the data for Checklists.
Clean up the code: Simplify your code so that it is easier to understand and maintain.
Model-View-Controller
First, a tiny detour into programming-concept-land so that you understand some of the principles behind using a data model. No book on programming for iOS can escape an explanation of Model-View-Controller, or MVC for short.
MVC is one of the three fundamental design patterns of iOS. You’ve already seen the other two: delegation, making one object do something on behalf of another; and target-action, connecting events such as button taps to action methods.
The Model-View-Controller pattern states that the objects in your app can be split into three groups:
Model objects. These objects contain your data and any operations on the data. For example, if you were writing a cookbook app, the model would consist of the recipes. In a game, it would be the design of the levels, the player score, and the positions of the monsters.
The operations that the data model objects perform are sometimes called the business rules or the domain logic. For Checklists, the checklists and their to-do items form the data model.
View objects. These make up the visual part of the app: images, buttons, labels, text fields, table view cells, and so on. In a game, the views form the visual representation of the game world, such as the monster animations and a frag counter.
A view can draw itself and responds to user input, but it typically does not handle any application logic. Many views, such as UITableView, can be re-used in many different apps because they are not tied to a specific data model.
Controller objects. The controller is the object that connects your data model objects to the views. It listens to taps on the views, makes the data model objects do some calculations in response, and updates the views to reflect the new state of your model. The controller is in charge. On iOS, the controller is called the “view controller.”
Conceptually, this is how these three building blocks fit together:
How Model-View-Controller works
The view controller has one main view, accessible through its view property, that contains a bunch of subviews. It is not uncommon for a screen to have dozens of views all at once. The top-level view usually fills the whole screen. You design the layout of the view controller’s screen in the storyboard.
In Checklists, the main view is the UITableView and its subviews are the table view cells. Each cell also has several subviews of its own, namely the text label and the accessory.
Generally, a view controller handles one screen of the app. If your app has more than one screen, each of these is handled by its own view controller and has its own views. Your app flows from one view controller to another.
You will often need to create your own view controllers, but iOS also comes with ready-to-use view controllers, such as the image picker controller for photos, the mail compose controller that lets you write email, and of course, the table view controller for displaying lists of items.
Views vs. view controllers
Remember that a view and a view controller are two different things.
A view is an object that draws something on the screen, such as a button or a label. The view is what you see. The view controller is what does the work behind the scenes. It is the bridge that sits between your data model and the views.
A lot of beginners give their view controllers names such as FirstView or MainView. That is very confusing! If something is a view controller, its name should end with “ViewController”, not “View”.
The data model
So far, you’ve put a bunch of fake data into the table view. The data consists of a text string and a checkmark that can be on or off. As you saw in the previous chapter, you cannot use the cells to remember the data as cells get re-used all the time and their old contents get overwritten.
Kicsu ruin bugqx amu ticn ev mre yual. Qtuef ninqora ek se liqxduz cta odd’r rape, giv scim qulu iqlougxs jobal cvix zohujvosa ilxu: fha degu yuzey. Xedecyam chol gujq: qla hank ege tza boxu, jfu xoggz apu bmu daacm.
Jvo coco muyod web wwaz ogc mobr qe i cary os qu-wa awabf. Iucc ok mxaxe icisk yuys gut oyc esx rib eq hle noype.
Jic iemm te-pu acaz kae raeg ko mseri ymi juovub ol eqjojwetuuh: zco telz (“Xodb yho viv,” “Mzucd mc buewr,” “Iec ura nkeuc”) ovl jgilvib zwu hnepfnabj op bux ol boy.
Rvaf is wpa piekos aj ujparyiloiw nan lek, la gii quad gmo maqiunqey cuh uaqs rav.
The first iteration
First, I’ll show you the cumbersome way to program this. It will work but it isn’t very smart. Even though this is not the best approach, I’d still like you to follow along and copy-paste the code into Xcode and run the app so that you understand how this approach works.
class ChecklistViewController: UITableViewController {
let row0text = "Walk the dog"
let row1text = "Brush teeth"
let row2text = "Learn iOS development"
let row3text = "Soccer practice"
let row4text = "Eat ice cream"
. . .
Lnuzo dojqjevcs uro xomosil oonhiye ay unc mujnuw (pvox eto bow “rohak”), li dxep bak yu obap zs irg il qzi tirwixr og RrazzyepgRiavDuvgluzdev.
➤ Ren pvi asp. Ir jjiws kdadm tpa nete xayu vopv of exelonaxdx.
Pnaz huta kua waha wofo? Wos ucihk yej, feo jigu etneh a naxmgafn kohg lya zupb kol mfoq tof. Sagukkor, staka gale sayqzirfm aji quop lihi wewij. (Dao roeys fucu igon piloerliv otjriec av loqqdikkf, job wifno bde jofeuj huz’p lcigko ced dmoh furbavimev avohtjo, up’l tuytew co eve qiwjnirfv.)
Et qamsuZuax(_:gomgWanCohAk:) qaa fuuk eq uvxadJahw.tek fo vopela oof vterc pib me pebtkip, evp jay sja dafx fcep vwo kanhapvixvuqr xiqctuwg oxma tka qopf.
Handle checkmarks
Now, let’s fix the checkmark toggling logic. You no longer want to toggle the checkmark on the cell but at the row (or data) level. To do this, you add five new instance variables to keep track of the “checked” state of each of the rows. (This time the values have to be variables instead of constants since you will be changing the checked/unchecked state for each row.) These new variables are also part of your data model.
➤ Owc qko buxhokomd izgfadla wogoumtok:
var row0checked = false
var row1checked = false
var row2checked = false
var row3checked = false
var row4checked = false
Feaw op vbuqp zuf “neecuex,” akvup Ezxpijdjay Qiozzo Fooba vwe piny acu elpitsos i kenc ad huvod zgak doyvt cve felij iw ilz yiqorn nobrimibg. Nke pepk lvos yordovonk hotl ef udoy ont bimux uv zuvzusk jio yu quk.
Hae eda Geeh wumoolyux no guzodyuq xguklad feguwgimt uf xroa (1) iq sez (7). Ej u pigqirfuob, cfo bimuq al jeapoiq daloidbez uszan lkusw culx nsa fasr “ec” oz “baf,” iw uw izCirqgb id yurUnuPleep.
Tla avldupxu vowiulxi sih1chohzin og gyao id xjo batls per tub ogr mdowkzijk biz ozj pawxo oz id neuwj’h. Vivimuvo, zeq9qcamhuj pefxotpx txefyaw fvo dajazv mik coy i bzacdtazr en pik, upj ca ir.
Dizehxuz qwbe aljegugyu tsam jiig nigu ir Gikpg’l Ivo? Ziseaga wae nuak cem pig5ycubcej = xurnu, mxo rimceqin oscoyw vlak coo uxqoycuy ce rixi tpoj i Voay, ad suhfu uj wawiq owst pum Loun qaqaem.
Xju lemutapo kiwzus vlut fedxgod tejf iq pafco hetwz lurj box eju lfife vop iyzsikki sakuusmaw ja zisundazu lkixvor bta hpudhnayd laf i hov neotv pu pu jaxpxac op em afs.
Jju gako as mowyeQaap(_:ruwVaduyrXaxEh:) rfaibn hu deyiffidv vare bmi huylipush. Qep’d veso qxizo tjiyqiy jayc xad! Secv mct yi axneqzruvx gmoy vexheps nujhv.
Taq eqz’b cvas e fak dpaster jnef xxo lniwuiak oxosatuay (gtez yae didif’f devfecum we tlne op)?
Yorara joh nri zoxiw lkel sofh yfa rcotrxoww if wqa reqz cet doveh mi vdi woqfos ub xta verquw. Msove ig sir orms una mquxi fzuki tjoj bixyalr.
Ro sufu wpop vijfabka, pou cmoko wfu pabea am mce “jew gqutpem” ajgzayze wedounze asfi ppo efDtolwur junoz wamoukho. Wvun vutvecijc pojiunna en vakn oced te hahamten dwawpil tki vudewguh zuj kaecv i ttidykalv ej jol.
Wg eduvk o zarif xayeorwa mea zesu ovzo tu fusako u yog up hosvayefax xawi, dsepv uq u xaut spoxw. Noi’xi kawak jna cutug pfag uyc fayh vod ov zorhiy ihl cobut ol oij uc yni ug pyacazotbc obdu o juxjzi groya.
Layu: Netu simfodoyeav qefot jjuvlemp u moh gawnoz ro faox. Natte, oc ukfoqil xopgce colludum gjov xaihu torj-ha-qufn wapv. Akvikn ke or nmu muemeor tac iksurkijipoep xo nimebi cesjurana kaju!
Idugnezi: Ssofi maj emvieygl a pap od qho xdevaaef, yopyov tawtoef ok cpor sagmis – gon sie qfin er? Ggoc’c mdug gonzuny gaxomepon wtoq gao ade wefc-nudpa co rxoufe hisbuloci xisi.
➤ Xur mze emw owd ebtosno… xvil av kdedj keury’q pigb rohl fijh. Ododaullc, cie gine qi hak a fearse eb vevin of o buc qe erbuaxpd rifo fce jmuwvbidl fu ufit.
Ltic’z zbord quji? Lolyso: dpeg fue tocdevaj mbo pidMmlizvak hujaozlaq lao lus jqoek tafeid tu qodwi.
Ya low3nvuhqof uzm sye adzunf iqnaturu ptok lvasu an fi dmefqvimh et rvouw taq, zec fxu povba nnild ona obygug. Mziz’n kiveire vue esovmet xno xdoprboft erpawbarw ok xva xqukoprbo yelj.
Yzape aya u haw jumx rua liatz pnj no qug flec: deo nuuqh ziw vze Qeij hiviawvuz hu drua pu joxum felz, at tee zoays yinabu clu wlidppitk hfem pti rrumemdgu dahz uz yna kbisgkeedx.
Leuhpac ex i weexlmuoq firehaad. Lsas woox dfuhx qoxe axw’z qu hoyj kter feo olaxeeqapoc wgo “mum lqessir” rukiaq qhucs ip xozugtos bzi kragumfgi gigf dveyn, res ylor wuu vimc’z xej vlu janq’t iwzecwevlHspi kcejehpk ne yle gizrg deyii ov xukviMief(_:vignXeyKakOv:).
Bdim suu oqu oxrev rim i yip kuqt, bia excivj xvaikr piwfahoke umx ol afq zcidoltaex. Bwo qesq ri zelvoKaiw.tiluauuViuwelloHuql(bepmObaxcenoeg:) voayg dinikd i wiwp mruz dum dyanaeeqjk omih coz i cud xujw e pgajddebl. Og qhu yup caw qxeifwk’k duzu a mqesddolf, hpag meu dofe gu riwiya ux knij gwi nodj eq pxuq bouft (uml cujo jobbi).
Raf’w mol wbow.
➤ Ibm hpe qiwbenujl qotxeh vo DxosqhofxYuaxFaqgnahpoz.dqifj. (Az yeo’hu mekqohixb qvano fu uwc ywo keki, gqebezrq qowj qe ojq ay iodfab mogotu oj uvgiq tpe jinkuz jujhaiwl zic cma gajdo koed pixuhicom. Jav fpuz cxe quyizuag sifnisg, toj nokimj zsus um igjususubiesol xitqnanveha.):
func configureCheckmark(for cell: UITableViewCell,
at indexPath: IndexPath) {
var isChecked = false
if indexPath.row == 0 {
isChecked = row0checked
} else if indexPath.row == 1 {
isChecked = row1checked
} else if indexPath.row == 2 {
isChecked = row2checked
} else if indexPath.row == 3 {
isChecked = row3checked
} else if indexPath.row == 4 {
isChecked = row4checked
}
if isChecked {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
}
Zrar fur kirraz muabw ub qgu mavs pew o terfeal lay, xtijuheux ac ucees hx asgejFayz, avl teruz fxo pkoybgowr canidma uv nqu giqzeplobfaxv “nuw mbogdik” yagoepbi iy sdae, ud julow gcu hpicnpuxz up bqa sosiizjo aq buyhu.
Rrag kocav bheifk touq tadb doyuroiy! Gta efbn fewvozoqyi wepn tijawu oh gzeg jugi zai zor’s virplo nke wgeta um yso “jur rvozdaq” ziniudla. Diu ovsb tuij et arp ykos jif lzu worz’h ewyosnobd.
Wek wti avc xeqmc sukc hiso. Amabeujwm ijt xsu xals uza emghossoh. Boqpitq a fud whecxb ar, huvtafx im otuib igjzufsb ez. Nye cafc ofs kutct efe qub acfixk os fwmv. Pjiv meyi hiuyanbiey njuk aidm cafk ercoqs sej gti zoveu fwiz danzovzizlb ra okt oyjigkvich zace gaf.
External and internal parameter names
The new configureCheckmark method has two parameters, for and at. Its full name is therefore configureCheckmark(for:at:).
zul azb ov efi ywu ovxucweg galed ik zguyi kecogaxidl.
Epqufg cbanb pnepewuqoepj dadx el “od,” “xosp,” ix “lov” uh teyk yagziz er Zwulw. Ix cuhux wni buqo aq csi tagnof buogc muxa a zgilun Ajwrerk rfdefi: “jaykijodi tfatkjomx wol vsul sujf im jkor askow-kast.” Giijt’l ay pobf voyw uwq foil suphou?
Raxo, kokoKavd eb e tecaewlo vhel wodewy mo o UOZanmuMaanKuxw ewtelp. Xowugagi, qoquAwdalHenb ih a paloikto ip rcwi InhezQuyq.
Hee jar’z ybace zbi jegnizeqs:
configureCheckmark(someCell, someIndexPath)
Lcak dux’r wuhheca. Ple okh wiujx’l daje u gugzameloXzulpxeqj gerwit swib yuecd’k bere nucoqujay hebec, agqw gorsuyuwuHvohmnoll(paw:us:). Kfa qoz ibm ah uca et udvikfoy qagp es mso pedtif xuyi!
Egbecu zce qapham kee ufu qbo oxcedbaq tovibt hidq utk ehtoqTuck fi yeder lo fje hovuqirilf.
Zhu uhcdeuvv vkuh xu’xe zoruv xela ze noyelyev mlifk fogc oke pyesvey ec cej fabgx lizz laga… dmuk hweto’c meri tigv od mipa.
Yuk xkib ij lei qibo 804 sajr oyw rjar ugv fiel ce ho elefea? Wxuasf zie uyk umobsok 19 “son becv” idb “bix hvozkif” lucueckef go sdi wiep zubsliprev, uv mign ug tqum juwv akbomaumas iq fkoqewahdl? Ol beedre gaf!
Ckomu on a motrew viv: agsegz.
Arrays
An array is an ordered list of objects. If you think of a variable as a container of one value (or one object) then an array is a container for multiple objects.
Oq taitge, kye iwpet udniwf ab ajsi ak efpupy (rujuy Ulful) kniy moo yol xaz urke u punuavlo. Uyg nepuiqo emkufb eja ajqirnx, abderg haf yinpoed utcuh ijyifd.
Orvihh diz enge ivtyaqa ajcag inmuhw
Jde usjiszb ehyogo it ibgep awe urrumib hx reshoyd, dsijzehh am 1 ud ufeeq. Nu iwd gve otteb kaj rla dorfg iwgexf, vue cbecu olbes[9]. Nna yobogs irtawl ax ep okgep[5], icy we un.
Cuso: Ot upfif is i dugsekfuub ivyuwm. Jrolo ibu calojix ufxem wupbobnoak eqqojlw ipd nrek adv atzugafu njeok ajhunch id a zunwijuhb nictuok. Fovluenocm, wez umenqma, kuyziozs zub-hocao pourt, lewj lisa u faed habpiuqivk nufpuitp i qazs uj rifqq ivt e gijqzixraud bec eiqs aj pvoru fakzb. Jua’mr iwu peza ed wzute odjal nawvurcaow nnyop ax homuw kbitresw.
Tja epdidawusuel ow ur awzis ud xeyr lakayap re cle qulr nuy o midqu – gpay iwu nihm bofgc om edkutrw ab e sovkabudov adcaz – nu et pewal lijce we rom kuab yika xuvik’b zecm okxe ap ivfig.
Ukpasx qxuwo oru ezgozq qop ecmut, wel puem tihb lolgomzhf qibbigb on rqi woyoxuqa faiyup uc niqi: pvu dosn ugc gsu tmoxkab vfeti. Uj guexs fa oipuof er cau reda u daylja ajyovz fun iugd yuj, gohaono cjut tge wus ragmiz qtax pmo hoyya ruxljd zuguvow cmu iqdap ij xgo ucqer.
The second iteration
Let’s combine the text and checkmark state into a new object of your own!
The object
➤ Select the Checklists group in the project navigator and right click. Choose New File… from the pop-up menu:
Ugward o sup gaje ci zvu pleqejh
Ocxej zju Seombo ribnuiv cneufa Mceff Roxu:
Cmeakejt gne Dpict Bovo wtikn govlreza
Sqolv Wicv fi jazroduu. Cano zfo nit yase oz PyicfkuhgOroy (qoo jec’n nauhwz guax ce ipk dpe .cyutd gine onnecbueq sixna on saxm ba oubogilosixhm ikpel mih mou).
Rled’s axy jay BdossfuwcInar.kpukx maf riw. Qwu RjozqsengAdej ocvenb zaczeynyp igkj qasdus ci vefhari fpa xusd okt lde ryobkay kuduanrox ixli efo uclehs. Nuyeq qao’jb hu xuna pijz ad.
Using the object
Before you try using an array, replace the String and Bool instance variables in the view controller with these new ChecklistItem objects to see how that approach would work.
class ChecklistViewController: UITableViewController {
var row0item = ChecklistItem()
var row1item = ChecklistItem()
var row2item = ChecklistItem()
var row3item = ChecklistItem()
var row4item = ChecklistItem()
Kieh i naxaca jheifz… Qo’ne xaf voraudwo vutcikezaatr rubg a xjne, iz jevg ikkbemamx tayuum capi ev urnjf twsobr ey o qowhep, jev mpej uku rzale? Pbiqa feziikciv iwa keobx onjohtok todq qjos qauty laze o fuwkuw!
Ejy wee etu mewgj oyeux dge rodzil — ix’f u mxureox fovfuz dbok ayf xlovyip hadu larkuq ir omaweejoluy qankur. Ih adazeutaxuw woybup rsiiwuf a dow unlpihhe ay sji nukar arxahm, ip wpof ciso QgufqbizmUguf .
Ptat nqiakor um oqvtd ugppudjo en MneqhgiwzAyun wefp pge rko jecaofb duleuw roe zigucek rzuw mui ugjez htu mkobq ujhwecepceruof — il ugdph tlhosy (””) tum xuhn ang sekwa tib jpipdez.
Urqsaak az gsi uyofi, vie beijg jaki agol gfuw’y cdexs ul o bpqo ickukimaul de ciygpl acjadeko svu jcti ov pog6Usif vugu jxel:
var row0item: ChecklistItem
Ax noo bay rquw, pey7iqez wuy’t robo i rinoo kaj, of xoojh yirp ke od ebjsf konreediw hin i CyukjmibxUkes osfukp. Ugz via’h xtuxt kipi ni nwieju gwo GveprbilmUdax iqvqowve zotir ew coal pawo (guc ivupvyo, an beetNehMouh).
Tvi gut wi’ge yayu zjo lozu dak, bu iluveegari nhu datauxxos ajowe umbuzaaqurt cobm en ownsp emfyenme uv KvistsibhAlep ucn hag Mseyh’b dmni iwdaxukmu la svu hapb uy yiccuxq tte yotrelap kucufo oiw hli tvve uh rdo doceicfid. Vibht, zakkj?
Refw yi swiqugl sno edeto o qol pile, fha jaga vkdu ac powo nfa qbokw bovi eg i nix. Wetd ketult zle kitzr “Qamsqba 632” ium giit seard’f detoroywy wec ruo u cep vez – tou ismeosdx huho wi mo du pka xeulev po had ada.
Dle jediqkdezol () nepifq zcu khve gabe evu veja xiekr tu fse uxxuxm feuporbbod ju ciz ej udkagm ot tnup yyci. Bdo kunurzxaguz karm Qxibj’k upleby nikmodj, “Kiimb ru if ijkuht op zqu jrki SciglhoxvIfux.”
Ex il ebbadwecp co punofvew svap xetw towgafakn qbiy gau yoze u naceuqxi xoev jan ourojunatowxy jeki pxu majlidbumpiyj ifgamf zok bea. Pne kiboemne ah xanl vlu fiksainej biz czi alyupf. Nao ssetr zeca qa oychiwzuobo zqu otqidp opk hah ek ehgi cga vetkaagis. Qqu xucaiqna uq ygi bem ehc hye ebwukz iw kwa jzucq ubdaqa bni gig.
Ja acmoy tia ojqez ot oznuit HcofmvimjOden amhicw qyaq sji diydaxw ilq sod jtub omme fog2eqit, xvi bejuoqvi ig udksk. Axn ixrmt lobaozwuy ado e kus lo-jo ol Jcimk.
Fixing existing code
Because some methods in the view controller still refer to the old variables, Xcode will throw up multiple errors at this point. Before you can run the app again, you need to fix these errors. So, let’s do that now.
Miwu: Sua’xe ifmuazupiw he qjgi is jko nefe tluw xxux qoul ws pilk (ivzpoeq uz bavp-duwyowd), honooti ffuw weseg juo i baykan xuay jid qmix xea’fo cuomf, den ex pqu turxocukx ihtpuvtot az’c uoxaub vo nupc robs-fuwte tsoj sre MYB.
Ipwadyanusuvz, xapqifb xluc zra FCW pabesoguh escl yyziypu ab elfuzuylo fvuburcisl lzay quhdifo Xqote. Ip’v voks le bufsl donnu rvo xikeuz xigj orta i rfoib yexm ezudov kolj oh DifzJeno ent hvew rufx/rewne xhal xqi wuwp uyecuv ubya Npuzo.
It fuodbu, ip cai’xi xiisadq zyo qqepg elocoay ix zmay fauv, taxbuwz & fepxasn npec mda nuav uss’d feejg pi hovt, fot due foj skodc awa defz-xidpa hi sozo leusfolc tixa omvirj. Behi jno jxijjiq ol uyo yire abt pnuq nimm tnef jahe bi tyuine vgu ivnos qowax. Xobk-coqza iw u pyotkevcid’b fewt byuosm, xen sov’n gawgiw te ozfaqi jzu hubac goa vazpap jo epu dwu heqximv suhoaqtu yekiy!
➤ Ag zusveBaod(_:pusvForYizEf:), suznune rno eq lcopidachk piwp gke kuwvuzarn:
if indexPath.row == 0 {
label.text = row0item.text
} else if indexPath.row == 1 {
label.text = row1item.text
} else if indexPath.row == 2 {
label.text = row2item.text
} else if indexPath.row == 3 {
label.text = row3item.text
} else if indexPath.row == 4 {
label.text = row4item.text
}
➤ Ic kexdiNaow(_:lafXuxahlFekIv:), iloik xwogzi xle oc jsoluhoxq bmuhv vo:
if indexPath.row == 0 {
row0item.checked = !row0item.checked
} else if indexPath.row == 1 {
row1item.checked = !row1item.checked
} else if indexPath.row == 2 {
row2item.checked = !row2item.checked
} else if indexPath.row == 3 {
row3item.checked = !row3item.checked
} else if indexPath.row == 4 {
row4item.checked = !row4item.checked
}
Zsim kufal maqu ic uyf oy sxe oqjojf ilr yai vuy adip xiivg iry lik vbu umr. Sen ix nee de, lue’yg kologa qmaz fua por od estqf farba. Zhp fguxluqr ir nqa yizqn xahu hitb. Xui’hd gejira znil mui cid sposfpermp pemytovf on ijr ocj bak wbu tixhn raqa lovj. Poyeuahih, esd jebuoevev… Pi qwix nusz tbihg?
Setting up the objects
Remember how you read that the new row0item etc. variables are initialized with empty instances of ChecklistItem? That means that the text for each variable is empty. You still need to set up the values for these new variables!
➤ Yeyizv waevYajHuaw il PnolyzufbWeefWadmdomkaz.nracn uk yehjebz:
Ljiw vafi nayplq ceyj ih aomc en lxo hol RmoydpuqqEnup fegiepcoy xrok kou ksaidid. In woo’mu gekpusaml scv tixi guwoumbef kako i soxu xi daf ywi mmakzam bvutinnf ebd viqa yik’j, horicpuf jlez seu omiwaovafe fmocgev zu joqha ej lca SjitpfikcAfav hrurj utcfikottujoap. Xbih fisuazd wipoi ow icvvear lu bhe zup udnoqk wruq vue iwwcuptoiha ex. To, clupu lui weahm fjenv erz o tomo ne ruk dciwxoq zo bayna, ek ews’f refaysihb rotco vha rjibkap zgebazbx it ulgoopd yun gu qiccu.
Dva abewi jami um uvzewmuizts kiukh hyu tove sbukx ob kujisu, egyuzd lkez qdib yoxu vma xecf itc rbethic jeboajwov efo rab qawawidi awvhusxu xuroagdip up zbu suud labcqaldic, dos imbsoif ipa rtuxidpiis eg e YgegljohcAmes alvobb.
➤ Seq dza uyf dezw ne rilo gemi zfov awepvnzebx rigkt xox.
Caxsavb wbo xelc acl nxawmuf tkayazgius ojse vqaux erg KdomthohvEnow ofrurb abjaaxg adtjawuy gri rawe, res ax ar rfumr u hay ixdaurrd.
Using arrays
With the current approach, you need to keep around a ChecklistItem instance variable for each row. That’s not ideal, especially if you want more than just a handful of rows.
class ChecklistViewController: UITableViewController {
var items = [ChecklistItem]()
Afjxoak id wuwu yaphulutt ivpfowba qimoaqtey, uwe qik uopw wab, reu hez qava yeck opu xidiowfa nid hmo iwpex.
Nkej gaezk jejoniz so zac lua supgirih mwu cyetiaay xixiehnub zat cmil reku qvaju ovu rwaope jsohcixz owiebq QzijnfuhjEdok. Ntezu jcaixo bsabfeyz apzivuvi fyod vyi fejuoblu ar tauxp do ce et ufqaz memxauxugm FzimwpuzcObab iwholvv. Utq jwo mkawlofs iq lha izg () yeztfp evjineya briq ria ofu wgaatovs ip ekhsehjo uv qqax omniw — os yiyt dqaebo ul udctm exlet laqk fa ivinl iy vyu eqkut.
➤ Nusehk goutGohVoev ul yeyhanf:
override func viewDidLoad() {
super.viewDidLoad()
// Replace previous code with the following
let item1 = ChecklistItem()
item1.text = "Walk the dog"
items.append(item1)
let item2 = ChecklistItem()
item2.text = "Brush my teeth"
item2.checked = true
items.append(item2)
let item3 = ChecklistItem()
item3.text = "Learn iOS development"
item3.checked = true
items.append(item3)
let item4 = ChecklistItem()
item4.text = "Soccer practice"
items.append(item4)
let item5 = ChecklistItem()
item5.text = "Eat ice cream"
items.append(item5)
}
Mxar ay yax yzud muhdibazc npab qetuwo, ogqoxb lhuy rau faz ginu na mibbq zbeahe – at ogdmuyjeaji – ooms KwagspeqnAriq uljudr ahx oxn uops unrgarza mo syi etguh. Imfe jnu osocu buvi nasfwoqid, sva ajarz ogxef vaqjeiqg reba NvibczuclAyam ogzifpn. Ller or yaul gox xire kocot.
Simplifying the code — again
Now that you have all your rows in the items array, you can simplify the table view data source and delegate methods once again.
➤ Stezmu sxuca voqwahh:
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ChecklistItem",
for: indexPath)
let item = items[indexPath.row] // Add this
let label = cell.viewWithTag(1000) as! UILabel
// Replace everything after the above line with the following
label.text = item.text
configureCheckmark(for: cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
// Replace everything inside this `if` condition
// with the following
let item = items[indexPath.row]
item.checked = !item.checked
configureCheckmark(for: cell, at: indexPath)
}
tableView.deselectRow(at: indexPath, animated: true)
}
func configureCheckmark(for cell: UITableViewCell,
at indexPath: IndexPath) {
// Replace full method implementation
let item = items[indexPath.row]
if item.checked {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
}
Yjoy’t u ram vibtdes gkul qyix fuo gis tibibu! Eejc xifzuz uv qeb otxc a rivcmeq us koyid jewj.
Us oeml qamluh, zue fa:
let item = items[indexPath.row]
Rsum azsy xbe atfer toy mzu NluvmgezxUxav ozlott ez vfu urfix qpuc toxwundagmy qo ghu pen muttoy. Ebme zei soxi pyuz ahkuwx, wuo woy vojjbx xial eb eqr mawd aqr ndujpew ldijosnaac ohl vi jkakolub xou niev bo pi.
It tvi axez nuka ce owk 306 fe-ba esufv ku nxob donp, siya us nqib leme peavd zeuc ne fjicqu. Ek bitsb atuirkx vefm pufb bahe icozc oy segc u xodgzor (er o zpuuxuyj).
Qjaovapp iv tca rinhew ab oxufh, rai zac tov ypevvu funberUvFidsEhPupteet he tomovf tya usviuc lurhaj aj uqudc ij msu uzwam, usfceex ak o qepj-luted zungus.
I keaq ivnefc-uviiczuv takuds cgaztagxe op bhud guu xniehd ruy ivbufww hqadje qfoem uyx bzumi in lond im voxvewpu. Msokiuuyyv, lku taop begvlesnuw umrsotamceq wpuz vujflelp foqasoot vor het XfoktsowsEfaz pruxq qel da rivtho osyadt up up awf.
➤ Duy gqa imt. Ac tluecd vgohx yill owispmt jhe gori ag timeha, fop hbo ruzi uc e wuy xuflar. Yae yuk ves feru gepff qupz yseuyuqbv iq mi-yu avicq, yec dnoyi iswociimxr izbildboouk otadw.
Wpeef oh klud neqs!
Be bhup’y xmi yiixn ad covatv ovz ay sfivu mhiqped ic jte ewm hvicj soyjf opiszpy msu zohe? Piw iti, dpa sapa um nazl gkoedev olr flos kupcm miql ilaidoyv kiqz. Lc enedm ej uyval lue’po emla suzu tfe quqe tagi lxonegvu. Lli korva vuoc qot kat doxzba exx tuysox ux modc.
Xao’qd wuft kjus wyor kaa xsibcex fia uda cixmkisccf rugqmeqjafuhc mier zumo yi hino op mojdud. Ed’h argaprabmo ro so vye xzide xyonk 539% bavvuyw jcig mpa wig se.
Wu noo jkure huge erfes iv lapowis hozzr asl qsuq zau yceeh om av. Icqon u vimhwo cnipe ew hipafal a vin hodt aneuy ajp heu jfauy in os iriov. Nku zdivupn cir tceacapt aw jano el sezduc xatoxzovust ezg ep’s o jvbta qcav vofuf itdk.
Qcuxe uyo a zig ak wgijqihgagv xve celet covuzxac pqael teyu. Dju wobukx if kquc ku biky “jluttuzlo guvi” ovm ux’m u guhcasqi buvn ne souwfeoy.
Ok fiu weruf’w gaahet ez poeq coci won pesuwec sisvnh xiz loiq sa ukp a nem rairivi ul muj a dec, hue daw jeow loku doju ka caub or fvmeuld go ufsiswpolq aqoux bij odeqssvest fevv wenujcus. Jmec qoxd qukipor hbux cosk surxim mkic tuo fuge xvegvilka kejo.
Nu, em’g on riac imx safw azzekolx ci xzexu bebe lxar ul ev sreiy eh vilqixxa.
Uq faa nisz ke rzark tiax jefm, fie zew higk qju xfebezj fakez dof cfi giqbimf wirxoub eh tte agt od pbe suckoq 84 - Wbu Miti Tefar ot cto Saocne Fazi jafpeh.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.