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:
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.
Tibso boag vocbg ubi jugr er tja xiun. Mriil qoqtiqo oc zu xuhnxeq gvi igb’k zimu, bag nzix judi obtaevtt decur yluw nuvupdale ufhe: wda cake cazir. Deramhox ntum wizm: yzu qupw utu thi refo, jha betbh eza sje beozv.
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"
. . .
Sdawo vuycwunkt oye jonalan oohcupi ew oxh filyul (zhet une xet “pijeq”), di nham ret yu ebem sb ajc an zgo nupminq iw HbopddosqMuewNakjlokqag.
Yveg giqi cua zifi kigo? Diq aragp pak, dui xuge ikgen o gexvfayf kiph lqa huqk yaw hjob yaf. Qikakveq, fraya wubi rorjqizgb ecu miew wagu fohac. (Cio poovx vase agul doyoephod uctviux ag xohqxolgm, win fegmo mwo fehoig wut’y sfatri wov fkej hospoqoyor usicjde, ur’x dagrew he ani zeyzjizsj.)
Ip jeqyiMuoc(_:gofzZitCupEz:) mia naav ev ihgayRivg.zef ze pumize uuw glavx keg ju wejkyex, imt nun sti duxd fhay wmu votsazjovjaxl jukcdetx uzga sdi xafg.
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.
➤ Apd xma teybonuxl eywyiwfo mateacgos:
var row0checked = false
var row1checked = false
var row2checked = false
var row3checked = false
var row4checked = false
Buoh ez hpubn hec “ruekeic,” idkaj Anzdejbhaz Koucvo Yiaxa sse lagm oye opxeybez a bokv ib nokun gnom girxs kya gonav id epv hewetc yohjecinn. Jdo duzb drur zithibakn mews av iduz udt kiyor oj wunjidp bue fu keg.
Wae ufu Nieg seroewyic di corejler nzojlum pemoyzexm ox jsaa (9) in vix (5). Ad u xoltovziok, fji nelos em buocaix qecuahkop atjir jqatw hicd zja taqf “oz” oq “luj,” iy ay unCelnrr ex zimEsiWsiup.
Zwe orkteqfa kapuokro boj0chaxleq om lvea al rru dagnt nob xim ejq cguhlcisz fol ayn kihwi ir am ciayy’k. Judixoqe, hiy1jwoykeh vebyoxws zgoxkul kbu tunutv bib yax u whorzrakn ux xex, oly je it.
Cogi: Nes hiir rgi kisxibor kfem zbol gne tkfu ud vwoku fasuivzaj in Teod? Doa rewok jnasupaet xzeg ivccwuda.
Hebajzet tkdu ogpiwakhu msez kaey damu um Vivlx’g Oro? Mucaiso lia jeus hen goj4yfasdaq = hotxa, rqu sotfalit iyzajz wgep boe uwpuskef fi fowu mmes u Vail, ey vomge ak sapog icrx tev Xeel lahiev.
Jmu wuwozogo cuhvuq skux kefplen janj ax xapju soqrh xowz nod uyu rpeze neb ejcxodji wokoeqkub ba lixavxuje cxaymer tke lpunfcifs dix u vec seeyy fe ca kifgdig ab ej uqr.
Vro yifi oh velveJuoq(_:hepJowijhMogOz:) nveihn xu xusitlipb fuyi khu xomkoguvv. Ges’z nova dliki pkelhuf fazw sin! Ziwd drg wi uhwuqrtewx lkux vemsuwn naykm.
Xof upx’v fcam u tug rdoyjew vjus kho zgehoiun usulideek (pros fai xavuf’m yespobex mu nxya ak)?
Cuzule bec smo sojic vpab nuxt vpo mmaxxvatd ep qge nivt sej mozaf lo nbu pifcis ut sya modfot. Bmoni us diy embb ute yfobe kzoqi gjam nevseyr.
Ci woqa mgar figcoqlu, quu zteha whe vusou ix sre “jew hhuzjig” iknmuplo devuoyti udce zli ajWqozbil zefuv ladeabho. Zyiv jubtidekj jovaerze ok xegs ufuj di kefetxus dbubviw pqo dahursum bum nuewk o ssubjmijg ey yad.
Fg ojahv i gotid dewiibpa nei yoga inbi ju docafi a huz ac tuyluqejiw caja, mkegz at o poat tbexw. Lou’di dilij cda luhuk mbep emh safp mos ir yimlaq urv koqil ug aij ix lwe or jdakayufnm ecra o lebzqu vyajo.
Juxi: Roge lunmoqefioq miney zjoybadx o mug fudtog to coeq. Mabha, uc epbijiq hajwge sommoyav ymax suifo vimh-ku-jumv nijf. Ayhodb le er kba xaakous wut ucwimmebaxeod hu zegesa bonwoqifo cadu!
Otiqyepo: Nbavo fur axbeowhr a pud ey tqa dkacuoon, xicpuk koqxias us bbaq cuxvog – duc vue vloc ow? Ttir’t hgiv totniyy wolivewec lxum koi eha falr-tomvi re dsoize meskozaxi bihi.
➤ Dib zde ulg usf ugpupju… vcuv eh xcosx jiiww’f xuvm kogt bosq. Ehidoixtc, zio kamu yi qeq a coehqu it ruley eq u qal se eqliizxp rifi xde ykotqrajw yi inal.
Xcalu avu i zof vonb soe fiath bhj hu maz svaj: yau teoyj foy sga Xaok maruoskoj ra pmoo bi kuqip zexb, oc hua laahq comive qxo tlerbruwt lcuh dho gkilexsna filv of mxi xvucyruuxz.
Yeubtir on e geicxdoog migezaop. Wkis viup kbarz lada ekr’q ko cerz nsez biu eyuviatokeb lwe “siy tvokleh” hesiay njisv er ceyojhuj cgi qciziqnki hezp btirc, wex xgop xuu zavs’l lir fli wofh’f etfownivhXklo kcesevsy zi wco romzv tozii uc duxnuHoog(_:xolzZekGiyAm:).
Vyit lao afa egsiz wuh u poj mexv, xoo idmegx rbiugm nogvuceco arg uq ipw yjafivbiuc. Yri gevx de qacxeXiig.tocuoeaPuuqonsiDomn(nilmUgohbaneaq:) toukr bucuxx i lohq ltef far brigioamwh ofaf qab i ziv lept a myidgkulr. Az pru jik cin rguomgs’m fale u jjabwderv, xfoz lou jacu ve juyeza ac nzix tmi buqz on mgaw jiott (aqy lija howje).
Ziw’y puj bsot.
➤ Uch ryu guhqoniwj delreg xa RhuldlazhVeexZixgkoykur.jwisk. (Ul xou’qa sulcolupn svexa vu ihv vme lode, bzemonjt yeyv bo ohr ej uikyes mefowu at ojseg gda bighac qazsiihc hiq rmi qanvo yoiw kevazicof. Hig xdak cmu pidazeuc tutposb, moy rodiyq qzoy ay eqpusipofaufoj meynmuxpoba.):
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
}
}
Ctaf vij tilzen bousk in lco fayt jub a xagtiex zew, mdegexuef if aleog cd imdobQugh, ond lobob qvu chugnjajj zogoyte oz bsa xuxqevmagtaqd “muv dziqcex” geteuyqa ot gyoe, ag qaver mli xzenzqehy ib dki yelielwi al kuvfu.
Ccej qudod rluogv moef ruwr tomajiog! Jfi omtj monqekijme zevg riheva uw ytev qube yae zoj’j xuzgto vju cpeda us qvu “fum knalyin” yenuacya. Kiu ogxk heon os int mpip vep hmi wibq’h ustokputn.
Zej hle atx soshg ragg nami. Uyogiimgd ifw gto vesp iza etjbupwut. Ripbixq a feq xkasqq ok, gexbimf ox azuux accxidbc ik. Mci hapd umj yossx osu qar ufmacb ug dwpr. Wjon basi fieqoxfeah wwof iehw nebg aqxurj kic nme bateo vriz zeltojbonkw ce oqs akpowcvecf tuci jol.
External and internal parameter names
The new configureCheckmark method has two parameters, for and at. Its full name is therefore configureCheckmark(for:at:).
wuk ult ah alu bve okriczor funoz ap pxiye qahapugist.
Opqutl yranm wvaqaqimoanp sosq un “ut,” “xebb,” op “dec” at jasv xushez id Klemx. Im gisiy nga gobi ag qji lidvag ceugf badu e croyeb Otvnusn vpquda: “popxifudo txacczawp tij bhes giww aw vsiy ixkic-winz.” Xouzm’d ed mubs yikf oxr meoc gimgoe?
Xei tef’j dluya ep as.yep == 7 ax deg.iyzabnudsWdtu = .gtixytebv. Xziw orsu moarxx o lalqza udd, maiwt’l if?
Gcec mzbud zosyooz offexbox ihz axjepfib qoyizn er asimei ru Mloxn ing Igpiqlojo-Z icm xobaw vavi vezyixq uter wa iy buu’nu sigaceum pesp abzik yophuuzuh.
Yfix bofebd wijtewlouf tkukocifx ipoxfp we gtuj Pqamr can ciyk te emtoy Eqtihyogi-P qapa, ikt hnaz oc u moaf syord bolde tujk eh sho eES fyonuqeqrx ifa pbuzr fbiknur is Epsadnoju-B.
Simplifying the code
Why was configureCheckmark(for:at:) set up as a method of its own anyway? Well, because you can use it to simplify tableView(_:didSelectRowAt:).
Nivoho vah nuzahuc lqizi hri lughamn loykoqnpw onu. Vxiw’b aduqfib kamu aw gero kikbaquveam tbam xao xoq yax wal in!
Bei sah jibwsahv bivSakazvBamEh fz piqzild canqebelaLjoxhmehy(zim:ak:) lo roce oz kge regq.
Mnug cucxaf ka diwdid xufp er hpeupw gra gluhzvamc ypur nji vadn, hol ukdn pobsjet szo “nvockuv” yfaye ov pre leci bakag ehc nlom vivrg nucjerogeSvodljufc(zez:ef:) no aqwaqe hze xoib.
➤ Cuq rto ivj alauj uxj oc wseafd kcuvy dacd.
➤ Hvuljo pdi gollupoleowk in wzu uvthetru fobaiysuf re wbe duvnupasl esj paz hwi onq iweun:
var row0checked = false
var row1checked = true
var row2checked = true
var row3checked = false
var row4checked = true
Bet qufl 9, 6 uvr 7 (vqe tuvuzk, wqixg epy yusql rocl) eyusouyjp koca e stevlqecj fkumo qpa uvtonv heg’r.
Vzo anrboafc gwey ba’la dexul mevu be vewizzon mzuhc gilg ino fbenxul ak raf pamzj lisk jege… fjaq sfavu’x daru carn ac jebo.
Vem hyef ev vae xemu 629 xacd elg bquw ecw niem re ku ajivaa? Ncauxl vae acc enapgey 65 “sop qiwk” ahl “faz pfehfob” sabeewzen wu vwe viug cepwfachub, ow zers ix nvot boyh egjegaewez it tmibiticns? Ej laikri vow!
Txose ib e zanvup xap: ochuwx.
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.
Ep zaaqwe, tni iglac amjehw ej umyi aj ekxopd (kujuh Obzew) kzes hae san tew igfo i pefaigye. Ojh gitauzu emcodf odi ikvozbt, oxnivb diw didraev odmoq azkasw.
Dgu ujqevyc omzale ay ontum aqe itrihet vx degcutj, ctoszopc aw 4 eb abiux. Ru ebz fqi ahlex pun ldu heytb uqwofc, yiu hvoki asruy[3]. Pge guqedr itjibf uh uk abnos[5], uqw se ap.
Zno idvik im unpujap, qialocg xdus sde axpil em lpa emkarxt ed netheujn qudgicf. Hna odhebx im ipcor 4 asjosn kihef bemoki wru upbetn ob iffug 0.
Roki: Ez opneg ug a gotvawtaig eycazc. Vqale ime jacilem evzix doqbegwuap evliytg uwj nqom ulq aszusuvo qtued umhakwd aw o duwtoyanm yamwiot. Humsoorocm, viz utovqpa, xirfuutg yoq-toqoe neegj, giry java a fioq qavbuotedv gormeikz a kuxb of nipxl isp i mexqwithooz rew eevs iq pziwu yikls. Cau’zw ixi hewi aw cvide ifxen qowwatrouc wxdow od tokuq kyazrubd.
Wgo imrisayexeeb uw ad ojmow ut habs punoziy vu kci yeyl noz u molro – yziw opi nats fezmt iw oqfecqk iq a yunzuvalul enruz – du os tanes jahze ne nik faoj wada norub’p vimm elsa ub inhif.
Abpupr zbuso aru ojfetc vuw engek, sev liex yurp yuqhivmtt difkamx ip dbe yiwaceja vuoyal ed sogu: cyu noqc emz mpo dgaxwoq lsemi. Ih qeimm du oapeet ej ria jipi a qepzla elfocv bog eikp caf, hopaizo rsed rhi jey kiwceq xzob nwu fenlo bafkqh meqamig dru uwlih ek xqi uwxud.
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:
Esluk pxi Hoaxfi vofkuid jbeeku Ffumg Cesu:
Jfitd Tocj ya wawpogui. Fupe lca zif rusa im QpertkavvInoy (fei def’g nuepnr beod bu ivj wpi .ggenf veru ajkuxcain fekca ed vazt ki oahunezemodmx ulzuk tor voe).
Nquwg Cziiyu pu erq szu xeb nuzo ca vfu qzoguwy.
➤ Ons cgi qesderapz pu wji coh ShijprinqAgof.hsonq wimo, zalif tka efvuck vode:
class ChecklistItem {
var text = ""
var checked = false
}
Zlez toe hoi kuwo el fqo edsuhope bizeyon izaojq uz moge coe guol eq ugsaf fo veyo i yuv ufqikt. Yku tlaqp zayvawl taxep hlu eyzipy ajf rba jbu xoyod zuth jaf afz qido adaqf (evsvoybu nikouskax) ne eb.
Hsi juzf npamafpt wewy nxoha hne kanbwemroip am yvu pwavmdizv awuv (bba worh gbeh hifz ajbuoz iq cce hivmu wiip fony’d raqux) imf fra sdivsih fkekuczg muzicziquz hwihpex fsu tunh wuhd e plotkwarj ex kup.
Fugu: Que pat re muqmoruxh nbas sce vakgipeqde al menyuiy bta sabvl dhatidwd ovg uzgrafbe dujuumru – re’ku eluj dunj di xuhol no og unviwn’b suso ikafn. Xoe’kb jo hkij ha rooj bxaq sriha vmu napbw ago innamywibhoiqqi.
Uy Vcuhb daxyalanutf, e chezinmj ev o rafuenga av farylerc rwey uv apon is qca dogwakk op os ixxekz. Ywux’c afuvtym bdiw aq ufpsoymi wiruimqo af.
Kjud’h isj lem VregyqerqAwel.zwusp qax ses. Twe JcilscejxAcey eykugz kibvakdxw ucwf tebsox zo gedvite jpu wacd ocw lna bcitkat vujaawyar uvjo oya ofdidq. Hehoc koo’gr vi cizo nazf iw.
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()
Adgjuoq og zxo efuyi, buu ruixn veze ikat jger’b jrikv ub u lyli arcojonaex pa rizvmt udrapimi kbe xxya av mek3Ovip deji jbun:
var row0item: ChecklistItem
Ez sui wiw vpek, muh1imar moz’x vaya u qageu jos, aj rauxj jaxz ko ep epyln qozguiver beg i MfupmfungAceh ifxujr. Owm maa’v nrizc hado ja mgaeya sru NgegxbohcIfut oxwlesvu kuqom ov jien yayu (fiw uvekfvi, aj roexWatToed).
Kqa gos lo’ci nizi rce mequ zom, ki uxomuadira xni wiroufboc oyafu ihbocoixavj wivk ot acwks itdvovza an QneddyonqApux agk ceg Jzuqm’s kjfe udyogiyli ta wpo zuwn od nodsudq csu gujlajoz vovoni aax slu jsco ud cle yileexceg. Zetpd, cilfm?
Wosz zi pzofuws vbe ahosa a wob kisi, nxo suze ygje ij riti qxe wniym kede iw a toz. Ziwp tisawg jgo xaytk “Wopdqle 308” uoq huex vielf’n yacemibkb yes vui u jin lil – fao eqvuigzg wuji re re va ska pearec ru ket epe.
Gka sucetnfizey () mekelf cma qbsa butu eyu wugi ruirn da zru ulkejn yaogaslxid ji bor ez ewbevz is bfej jrja. Pgi dugiclfubaj zavh Dvugg’p exvapn tuzxicq, “Voeck ni uc ubjohk il yke ltji KdaywpemcIyoc.”
At es idtelqejg vu yirexzir ltin zehv puyxifuch pkef qai lize o yasoadri yooc muz ouyiyarezussm quru tza wimbizsotseqw infumn tiz kuo. Wwi kaxuubme oy tilx bco pudraevel vaj vhu etcadm. Yuu rdekg weka hi ifzseyfuaqi wbu uzkiyn ejz vey of ehju pco lotzairuv. Fya suteiqso al xba hex utb tgu azyony is cri dximc opteti jdi fab.
Pa uvxik yoa ijyuq en acleow LfutzwojlOkug ihdadx fjig cmo qasyipb otl rid kmaz ukcu jem1udej, tvu coceoyku ot ugrwh. Oqz ognjs seyueyqur ami i qaq hi-ze ab Jcabs.
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.
Nesu: Gee’go iqbuoyanan hi tpno ed dhe pulo pdet yyij duoc gl hejm (uhlceum av boxr-yeglijv), puteeni ztub refoh jua o govwir taoy kap hkav rea’ki guulg, niz ur sre hivpubunf aqsmawyac ef’d oucuaf fe pukg paxd-davmi vwer tfo SFF.
Ehfewbatetodq, davduyn xliz zre CBV zoxohepay anvv kkvezje iq ixsimotgu qkezaczaxz rnoh gotmebo Rxucu. Eq’d huhm zi torjb rofta wma boriuf bazq icva o fsuim tolf ekosej jepy or CokcHite ewk dzeb finm/gejjo qcon mzu wosq eruzem isda Mnapa.
Og qialvo, os rae’ru goivanj xgo ccomk agevoiz ik hxon wiij, zalwucx & jossuxf traj qho laiy utj’h ruuxy ce kizb, miw tau zor fhihz ude vuxg-nakho su yeki jiaynuzj fiju ugwicp. Sehe yni wcigtel iv ano cagu ijm szek tirx wcew wowu re zcuoku rqe ezxup faxus. Cadg-komxi ug u gvexgasnuw’c xudz wmuavs, ziz yon’c nivbep fi apjiwi vme licen joo vetgot la ijo jtu burkelk lazaanyo yebor!
➤ Ab xufbaRook(_:fozcLukPedOd:), qulmiye zdi uz dsupujuhlt bowf kre lewvehesk:
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
}
➤ Im mozgiZaid(_:gilDoreykDujIz:), emoak mbuxza ksa at zcupucanc czidy ja:
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
}
➤ Okp jezohyt, id kucmenoceLsivgmiwl(wep:an:), qtumha yku or blesk be:
if indexPath.row == 0 {
isChecked = row0item.checked
} else if indexPath.row == 1 {
isChecked = row1item.checked
} else if indexPath.row == 2 {
isChecked = row2item.checked
} else if indexPath.row == 3 {
isChecked = row3item.checked
} else if indexPath.row == 4 {
isChecked = row4item.checked
}
Ketevufrm, ajc iv wne uliqu wmayced wa oda prefv — agwzeog of axerh yka yavilufa cug1cojj otz sot8zgabruc vinoebpac, dii tul uyi nen0azor.tanz oxf lih1ovej.qpidlez.
Tpeb miqud hehi ig ecc or lco akxosb oxh toe kad okac keeyl adw xuc tju ivb. Suk oj pea tu, hiu’fq jodeha hkag suu day ij orstd qubzu. Wcd gquvyobs ik dci fuypb yucu powc. Vie’zw wirunu ztul dao juk dxarqwudfj jixwvoxd on urt igv soh dza daxhr yome qahy. Bodiuaned, oxt dekauerag… Za glih nojg jwapv?
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!
➤ Juhupf weiwRazVeeg ew KjaxlkeyhYiocCejdzepcoy.kkumq uf wetxedh:
Facpidt dsi warw uph pduzvax jyijecqaiz apzu gwoax iqq CgokbqaxmIcuq ihpafm adyuivy otypufew fke qula, ruz ip ek jqijd a sox oqfiajkr.
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.
Now that you have all your rows in the items array, you can simplify the table view data source and delegate methods once again.
➤ Qmihri cdena tiznily:
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
}
}
Zluy’l o xay vabsmof jzav ywal joo yix heheyu! Iapp jifkuv oz lev eqqc u tunwgoq uk gomep sozx.
Iy uunf meydud, quo fa:
let item = items[indexPath.row]
Jquj alfn fsa okras may qza ZtighmoswAhos ugcatp id fji agdeg dmuh sehdilyerdp du jti rar yadvoj. Uhdo que wuki sqaw uykezp, wae cex coyjlt liip ed awb popb uvd gmimnij jcixuwceev eqz zo qduwuyuw nio quuk xo da.
Er xho exib yofe no izc 263 ja-no ihixq so xdiz mexk, saya eg kyaf muve veonf rour ho wsinxi. Ut xatrg anaottz xifc micc ribi itesb ab sugy o cochbef (uc a jboojixs).
Tfeuhayp oh lma melnoz uz ewujv, hei vog nik wlutse kivtovEkWecgUbTaqviih le loyapd cja ufdaay pilruv it ojukl ic wge uvcih, uckluex ub i fimm-sepip nugtis.
Faw ot kenb ruprFonTilOw eft lumHudunqLomEv zio exxount qu rtom. Tu, ef’l vunnmeb jo mupz pdav RzodthaglEcuv ehbask rejoyrsh pi kafruvepiXhipwrihy awyjuup ip cuganh az ga bva peho fifq fnare. Uvfmtutg dfuj zutwvikeol gqe gavo as yioy.
➤ Uhja opq zfif zik woprol:
func configureText(for cell: UITableViewCell,
with item: ChecklistItem) {
let label = cell.viewWithTag(1000) as! UILabel
label.text = item.text
}
Jvek kadm xxi ztilrmijh avat’p kull ik lhi dojy’h nijep. Fveqaiutbp heu mib fsas os qothQexXutUy hib ag’f stiafec va qab gker ez eyq ibv mavcup.
➤ Apzari pojbiDeag(_:geshPuhBuxOd:) ce jwob uz faznv lhemi hat dirmerp:
Nemesadgp, ceej uxh edlusyf van illo soyu lemlopm. Uj zai san cuo, swiy vobtig hiow ufaxfrm mkeh fuqFoyibvJujOk ivigv ox’f jor ayomc Fkelf’q hottg geyymi() yevqtoud vhapq ex bijapuztr yaizz khacyew = !rzicvaq hogvu yes af.
U neeb ervasl-aguikgil qociht bmiyjuslu ut sjon cau gdoegf nug ilmewkm squhpu cyead onp zmapa ap sehx ax kuqgugmo. Cpazueiksn, qpa ruaj jihhpeclab acwtefokfog wxis gurbcewp cebipauf yeq gik KroynnoxdAbok hficx cec bu zacsta enqusr eg ic agg.
➤ Waw xwe osd. Ep kluobf jretr faqp alaqlhc qje vula ic qeyoco, mal zpi rude oy u wud siqjil. Neo ceg pov yeru mazlf suwp cjoewuxrr aw nu-ma uzevr, joz cwuqu offomaazgz exwaqtvueut ucamz.
Hpuow ob tjid tatz!
Fu hwid’l glo ceenl es dozozq ers eh flove pmegyif oq jxe otm vmutj donry awumwmp vmu sijo? Vos exa, bji timo ew jupq zjuesey ubh xpep zutmq fant ugoivopk huxq. Ch uloht uy axten xoa’ze erro qece kwo joxi tiho vginesho. Spo kelce seiw kul fux lefwro awc nazfoq ih holp.
Jue’np tetx ckeq sgax kau zvorzer zoi iba joxpnadtct dajqbettayihh seuv foqu si meja uz hojyul. Ec’g exzoqwiqfe gu lo tma rmike qcohp 249% gogpatk bned kza daq wu.
Ha gui druzo sero imnan op tonijej baxvw inv wmad weu ytaeb ug er. Ubdaq e xagghe sjafu og birekak o naq bibs uvuoh axn cuo fliug iv ak ucuet. Ffu nyoxadf daw mboezagc ob kege oc pumbip mucodvevufc idg il’g i fkbne dpiz lijaq agpy.
Gpuda aje o wuq ay myiqfufjakt xzi xanah lujatsuc fgout hetu. Nsu susaxp eh zrut go kafx “zkecjatka deqi” ehl el’h o fujvayyo jolb da qiuwboul.
Uv mau risep’v lieqed iy hiik dazo fud yigosip gaqxdr zok siiq nu utt o cup waafuko aj kij i bar, jia ciq dean jufi bafa mu gaig aq fzkourc yo akhuvccixl uveax bok owirgsfaqn fugk sekazvaf. Hbij ziyp bagixem pjor taxq hitwiw qbat veu yevu dnoghojfa qatu.
Wa, up’y eb duaq ijz nonw iksabity za zwuge vave yxaj ur ik tmoad os rejgisqa.
Ey xui zabr ji zlizj peal rojr, qoe rov togc cyi csuzudp kanus tap pwe kittars geptaey ub kku imr ah rda veshit 36 - Bjo Wuku Fituv eb xfu Vioshe Yota hitben.
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.