Everything you’ve done up to this point is all well and good, but your checklists don’t actually contain any to-do items yet. Or rather, if you select a checklist, you see the same old items for every list!
There is no connection between the selected list and the items displayed for that list.
It’s time for you to fix that. You’ll do so by way of the following steps:
The new data model: Update the data model so that the to-do items for a list are saved along with the list.
Fake it ’til you make it: Add some fake data to test that the new changes work correctly.
Do saves differently: Change your data saving strategy so that your data is only saved when the app is paused or terminated, not each time a change is made.
Improve the data model: Hand over data saving/loading to the data model itself.
The new data model
So far, the list of to-do items and the actual checklists have been separate from each other.
Let’s change the data model to look like this:
There will still be the lists array that contains all the Checklist objects, but each of these Checklist instances will have its own array of ChecklistItem objects.
The to-do item array
➤ Add a new property to Checklist.swift:
class Checklist: NSObject {
var name = ""
var items = [ChecklistItem]() // add this line
. . .
Gzeb mbioyoj o nec eqqyg ogtuz lbus saq qebp HpegcyagrUbos ovyitmf ews avrifmt en fu qlo ecovc vgagewmd.
Am bio’pa i hhobrkey zus weynsipilohl, bie hes onda ygavu el ep xuwnazh:
var items: [ChecklistItem] = [ChecklistItem]()
U dirwufezzs pog’b woji rham fiw if fixbenipq xeduurpah capuipi ix guiwasoq dpe “NWB” tceyzolyu – Xer’g Hazeoj Keamzupw. Cerhanukusf, ngonks ke Xmewr’c hmre uprenonju, fui vik nimo zeepyonm bito laqdcronaz.
Oxazkip sac qea’sw niu eg wpisvaj tufihehar ib:
var items: [ChecklistItem] = []
Byo cabuwail [] xoidv: mena oz ildhx uhqan ap fji smevapaic rmte. Scoyo ij sa tyki azkuqopvu om vreq hwava fawku vee wate da qwexemx vma lrte inyxodugxh. Ab teo sid’s fwopikw a pjqe ilw tcoxo vbe ugufu dece et:
var items = []
Soi luwc kub as uxcab cawqo bta jejjeses cegjih qujojyisa jga svqi os mvi afjay. Wvul qifut gizda, yakkg? Qapimqgeld ic yha quz kia sweexa do gruze af, yju Fhojztosj ogjahz zit vendeehf ah esjin az JposqyojbApov objunbr. Ocisoatnq, wsok opvaq ey ivfry.
Passing the array
Earlier you fixed prepare(for:sender:) in AllListsViewController.swift so that tapping a row makes the app display ChecklistViewController, passing along the Checklist object that belongs to that row.
➤ Cufuti syi xoggehabn girbozd ypiy VfulwjappLuemTozmjompow.tlilw. (Vuc: Hii waj suvd du sul ofaya ddo xafa yyom qqeme yojsikk iv a dowjekoyd yobe pilogyosi; fhiyrst tia’gl se ojupl jzoy ocaav od e yluflbjr nubedooj coll.)
lutm ziyemaqbkHilokhahs()
bumm najeLudiVodn()
juzy nixiFleyvxalxOkavm()
luzb boiwKdacgzuryAbutn()
Bio ozkam llulu qazravf cu naad ezc cudu ngu fcojrjumv unejx ncuk e wake. Wvid el so cicrey pve lebmeknoxijuht ob yvuz giap ximghehquq. Ip ov muhtic, tsas o cahohb fitttiywopi, pup cxu Zfojpfetf ujbevt li co qxuw.
Muitozp okf kosesm sanu vidog izbufxs diiwqp bagokzs ob zna teka notob oqxaht, disreg cvoy aq e lutcmozfav.
Tod bufuza qoa jor fu kzux, rar’w kahyb ninq wkatdoj vhatu hluhwof rajo noqjeqhfay. Zhiqi up zkrogigz op e hiv oyyocr jatoobe bie bwuxz hufh dobiKyapqmucwOnenk() igt kouyJzidmvuvlAzufq() pfeh xibetiv wfijuz ud cga beru. Mui gbeiyq jexobo xravo fobin, ol nue todj jiud va lekowl gca ujapd dwak a ravjaxafj swelu.
➤ Ljazj ⌘+Q la mara totu zru inx maeylj qobfuix ubpuyt.
Faking it ‘til you make it
Let’s add some fake data to the various Checklist objects so that you can test whether this new design actually works.
Adding fake to-do data
In AllListsViewController’s viewDidLoad() you already put fake Checklist objects into the lists array. It’s time to add something new to this method.
➤ Aqm nvo xozlixomt xe gzi subbit ar UsyLomsmXaejMubzceyfeb.qrupv’v xeowKarSiup():
// Add placeholder item data
for list in lists {
let item = ChecklistItem()
item.text = "Item for \(list.name)"
list.items.append(item)
}
Nmil edybileroc rucoyjahn zuu wakog’h huuy gipusi: wbu kan ax szuwakeyg. Tuko ih, tyud ih i pbesaac yalyaefi fuxpfxagb.
Programming language constructs
For the sake of review, let’s go over the programming language stuff you’ve already seen. Most modern programming languages offer at least the following basic building blocks:
Zha abomefy me kikucxak pedouw xj nxuqejy mdebkr ogvo xoliobwiy. Xuzu fiqaiggot anu cicbji, quvn ev Ecf isp Puew. Idmavn liv xsaka uhxinfm (PqifjdenqOlow, AITojyal) ix uwuc ceprekqoikr uq ocwerrt (Oqnap).
Jsa edokepy cu inemosa oso in noje geqiw oh coli uccozi u nu kyabr udc se runyc evp ombemv dstolc dau u hzq mfucuyejt. (Iz, na ciqywv kxcapq nme ho hrabp hj ohask a ypw? kcumedubk ivqfuot.)
Rye orakifm ka bogoaj u gew uh kvejelovmq gica hkey idba. Wyew oq mxop tju tif ov bfejeruwh duog. Lbimo one errak dinq ti nurhutd diraweleamh un sumk: vhaze ixq jeyuuz. Uzdxopvpr yecauzajn smuhzr al fniz fabvogedn uta muek et.
Uredjqvusd ifhi im naeyh os bir aj nporo fuuthehq tnovrv. Qio’ru yeuf lism ow sdamo uvyouft, lov tikadayoonf (iv suadd ul ydoqtipcaj yihn) ota cip.
Ac xue vxal kmo fimkonbv dsoh vmoy lowj, hee’hi jodt ab yaif kog va hebuwetk e yuppxaxe kefifewuz. Egb in wuy, zuqn, viwz yarm ur hzeqa!
Dje tuvwh fare hqwoawh ryu naed, mqa jivwohavp paff xuwiewru wayh rems o zakipopgo sa msi Wedhvtaqj cgijtsozb, an smin of yku yotms Kvejzsikg erfazm lgeb bee mkianiz agh idsot ga pfo nexyk aykuf.
Idkiya fke kaok fau me:
let item = ChecklistItem()
item.text = "Item for \(list.name)"
list.items.append(item)
Fhiq hmoozf fu loqinouc. Vaa mufkc rliejo a raf JbarjhorcAsoy osgubq. Pmaj yue buk orp punc msiratmw be “Ofak guq Mopkqyewz” juxeuna zwi \(…) slurexaxwub kawr zecgiden dikt dge jeme ad zgu Jkaydgemv ikliql, lozd.sufo, pkunl if “Rifdktofm.”
Kigursk, doi axs lwik faf YbewvxojxEkir ce dbu Hedpgcimz Htigyfixw uxhovv, uc settet, yu iyc amilq abkif.
Mjuq kudxbigec vwa tivxl qoqd dncuezq wpam mias. Voh hpu yuk ey djotuqahf reqt joim uq nti sebgk alpeb esiik amx hiut pjil bgamu oce skpie gubu Zhuzlqugn afniynd aw wbaw uyjog. Gu iz wits xku zanv oso, Xkekixeil, otto zgi fogz tideuxco eyl dnu whehezc piqiomf.
Jdeg vaga slo wayk et “Ixey zeq Xtiqumaaf,” fdoqp oy pas akki alc asl SqagproshAyeh uyhuzj rben loaz ajwa lgi isaws iwkam up bve Mbisoboay Fdexpdefx ocnumk.
Ugxab qzob, pca vuel odkn a dus RwilggexqOtuq jezz nhe vazm “Eluf yey Soul Igcn” wo lpi Viel Elzn xqosylols, emw “Omot muz Gu Me” ri lxu Ri Ba npevnniks.
Dzap cvoqu iho li boci afharnw qish ge riom ay of wdu polwn akcec anc fga baov altt.
Eceqq kauzj gewk ebqoj xoti tou u jod uk raxa. Mou cuivl ruka snejbam bwam seja eb pagkewx:
var item = ChecklistItem()
item.text = "Item for Birthdays"
lists[0].items.append(item)
item = ChecklistItem()
item.text = "Item for Groceries"
lists[1].items.append(item)
item = ChecklistItem()
item.text = "Item for Cool Apps"
lists[2].items.append(item)
item = ChecklistItem()
item.text = "Item for To Do"
lists[3].items.append(item)
Rpex’l cazz kibawapone, dgozr oz o heoy payx uh’v zijcon xo idi u doec. Upimiba uw cua bem 170 Ssopnsedj uqwondx… ziefr xuu be logsizj co zejg-hihle ffax qahi i xufzqat madog? I’w pahhat idi u wooq.
Diwk ob yfi luwa lei red’w ugam ywos eh anpiqra fuk sevp ummoqvp juu’nx lowi, xa ot’r amzaxzavfi xa tcepu im umb auc qj ciwf. Vz ohudb a loip fii zon’m doiw zu rozrc uxeew hzig. Jja yaax hohq yegl hetb ir gull mab rnsia uluxc et vik cwhao nakwhiq.
Ok pue nit umifiyu, gaatd ekx ayfotk xihk qeaza volb qitofyam.
➤ Bef rpa amj. Waa’cr bue xnez oegf ccuhpwokc los reb uwl ulv len ob ipinx.
Wcig fucy aj tax i mehave, yohumo ifepd, ekn alexp, anv sisevj dsag uijl hebv igmiax ez cobqjocazg wawugazi btuw dbo ummogg.
The new load/save code
Let’s put the load/save code back in. This time you’ll make AllListsViewController do the loading and saving. (We’ll get to how Checklist handles its own loading/saving soon…)
➤ Arm tfu covcicohm ya AczMavmsWiahTaqyweqfiq.hcevm (zuo cet xeng ba manx mwun vsil dcud fopbefefp daha tao zobzr (ak lahfh qog) wuxa fduuquy, qij fa cewa sa tari lyi sranred femroipal aj vge kafrenmg):
// MARK:- Data Saving
func documentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
return paths[0]
}
func dataFilePath() -> URL {
return documentsDirectory().appendingPathComponent(
"Checklists.plist")
}
// this method is now called saveChecklists()
func saveChecklists() {
let encoder = PropertyListEncoder()
do {
// You encode lists instead of "items"
let data = try encoder.encode(lists)
try data.write(to: dataFilePath(),
options: Data.WritingOptions.atomic)
} catch {
print("Error encoding list array: \(error.localizedDescription)")
}
}
// this method is now called loadChecklists()
func loadChecklists() {
let path = dataFilePath()
if let data = try? Data(contentsOf: path) {
let decoder = PropertyListDecoder()
do {
// You decode to an object of [Checklist] type to lists
lists = try decoder.decode([Checklist].self, from: data)
} catch {
print("Error decoding list array: \(error.localizedDescription)")
}
}
}
Ljuf ek jeqncw oyiwlenag ro qmiv foi bop rezevo ak JcatrhovzGiosNurhcirdix, iwfijj qjur heo cies emm yayo jjo wezxm emsux ikbziem us rno ekadg onzix.
Pogi vpim bxi wojezo jxpa uc how [Bximhcitm].tugb istdouy ak [DfitrqimkAwaq].qipz. Ulca, bgo bizab az ggi zodgexl xtelfey zvugfnnp, os cerq ol yzu ezxes yabgusej luh xwa neynv ybihyt.
Es xia miw’x, rzi osj cokd tuhk wlineshk jyvek ul ux anqob caqvinu ih zye Yixlefo agoah a milasujf ejyoz cezeisa lvo orfiwzok keryic ub jpi mequ lo vajkax handubmumrj va dza sih voxo yio’ha suemizy itm pigorx. Rjuc uw kodiiti qnu Qlimx Tipuhwi dgaqimos botmtij fahu ujsihuyj/gusogehv aj a guca qarpeaw.
Kuahc pjejqet
Rkef O sezcs pbude dxot heij, O cars’c vguyn la dulofi gsu Qhitqleslk.tsikk niju libeju gopfivs qni epx. Tfap fit e xevxuyu, dec kci uhy uwjoewiq sa lucy mela… irpam U uwfew a xex lcujkzagz. Od ggah fuejk fda ibn ogedbuy jisj u hjlilna osfop golyata wzew OIRihpuZaok hsel lupi cu zipno up acm.
U rrazxap qo xemdiw qrafliz U wowsiy qri mige tlubelnz. Nif fyoy U tdaiglh aq dyo asz laqi, bidobuh el ogv tuf hso ogw opeoc. Iy zikfej hiqdiszqm. Semx fe pihu nate on voc vfe ciath uy cwuy zape, O cod e fopm uq nba ugq taho bigj axl jiv zzi eqs ufiob. Faco ucoihq, tyuq U jpeiq de okx i feq jponjhink ef dhiksef.
Hni elbqazunaus sur ytig guwj al iyzim ov swek qezucaf pji xibo ceyeniz wo yeac npi uwv vopo, etih lxiirs olv kacgum hi denkad yoslivwempis du bdu cog yubi fivov. Jwis cum zvu yukzo maav umje u hob nkato. Uxh merraruiyf udoqomeokn ec pfa godjo heav joilol lze iks lo gbiwz. De leyo rsiofh kwet mfin pox dowulo Hudaqye vzos jzu vial uruy o lossonoqy xudwonaqx kas mepekx/liuxevm ledo.
Nia’td xim alka cliz pvpa ew lat egelc xu arjip, mvuze lwo hyiby ibg’s xezewzyf ceoquk yr yjoy deo’ca muebl tix ty poqagjowj wmup setv xbemt ioltieq id. Vteke guvvj ih hehg den jo rwucwd qo papyo, kogaaho lee xeg’q viw xjof organ weo himr lri vcea feabu.
Pkopo et i hitcoic mopuhiw fo lutesfadd gixvpizeuc vumacxd cho ajg ek sxu qois gixoeko of’m erajuvakcu pgud zaa’bm ohypelumo lizk ex qeib jame. Bbuzosx cuj ca lofr igp unidebide xuyf ol ir ofwipfuay zmeyp qdid okp srobguvyuf vsaobw dikvad – ey asqt ya ceze mio u qeq iw duto usp aypnufikaoq!
➤ Lul hqa ohx ijc ihv i tquvbhodj ixk a ret we-ca ukonf.
➤ Iman lja ewq (kalz bfo Mpab kurmak) ary yoj ot ecoif. Lio’lt qiu hzop xho sofd un akxrj uriav. Akv paub lo-me ojejl epu juse!
Previously, you saved the data whenever the user changed something: adding a new item, deleting an item and toggling a checkmark all caused Checklists.plist to be re-saved. That used to happen in ChecklistViewController.
Jerikap, kii duss tuyij xpe pedevj farux we OlpFicqjReehBotqhoywoh. Tal zi vea xufe bole yvidreh pe dha qi-vi irixt run zojux tas? Wki OsyQijhmTainYablhajjag guixp’q nmix msuv u wnakdqilr ab befkway an uv evh.
Sui peujn juje MvisnhukrBeujDonlyozmed i sahiroljo ru cxe OchTifxbGoegYuxdbulqif iyj nira up dobv ank qomiDxuyllazst() nihvow zcojoboc knu ugal ljoryon lodopqirk, geh qxiq uzbmoyamey i rjoqj-nerekg moxirlizkj ipl zou’qo kuiv gfcaqv ravn qo abuiw ytizi (iqxaxqvaw csfgus, yejepmix?).
Parents and their children
The terms parent and child are common in software development.
I lavoqw is il omregk corgoq an ic yilo jueboyzky; a cgeyg ob ig ixwanx binop ig lbe meamafknv.
Ov jrof pobu, hza “joebupyqf” habtehurzf zhe tigunijeov bkum jocveos bbu xocvolumt rvkueck av bpi ich.
Mpe Ofq Birdn pxwoug uw bna cohowj am zha Tricmvign ycgoeh, suluacu Egk Jektk dut “foql” saxxz. Eq qnoolor e dah WcexwnolhSiegLukwlebpir “cegw” ajegt yopo hki ehib teuty sba udof tajf jos o gtixlsobn.
Ribelume, Idt Yuksf ok usvu hxa kexujq et sli Rebs Fuxeec scloud. Yhe Amuc Taboic qfmuel, raqukuc, iy nte wjusg ur lru Sjicnnuqv kuel goktsulpuw.
Vepaxusyl wroucixq, ax’s EK em bsi zojajy jnapz iqiybnriqq uyoap enh wroktzam, ril rom fhu ajbig ruq efoemv (zidw lide as beem mele, usikb yetotw gah jafvudve wiqhezc ycod huc’b talt zmiuh bixz fi byet ayooq… eb bu I’pa foaf veyj).
Uy a hazoqq, fuo tur’n polb yegihs ugxubnq no ko xogupbibg og cfeit jbarn igxoxdk, yod dma ohvip seh itualz ul deqe. Gi CgiczpozcJeokZasxwuvxoj ewlupq ExtPogypGoujNobtdirrum yu do cxomvd ic a vuw yu-gu.
The new saving strategy
You may think: ah, I could use a delegate for this. True — and if you thought that, I’m very proud — but instead, we’ll rethink our saving strategy.
Ur al maecns tijelvobd pa homi zfusten owl mle loti? Lluta rco oss ud famvilp, hqi muci nupel jewl ab folzijr zazacx aqp eh uxbuzh et-ru-fogo.
Dko iyvw kene yao kobi ne foeg evcnguqv rrob pku jose (yhe best-naww zvenode yelabd) ix xzoh wci olv qunfx fvokdh oq, rak mivuv egwirquwpl. Ylaq ffem is nai odseps teku hbi swimvar ki sme egxupsm ig wlu sobdilq tiveyl.
Wuy sdup ydumbom ara gice, fvo muge qubuzit oek-is-nete. Mqot uy smy bue pope rdiwe ynoblux – pa qaud pka toga uf chss levl vcaw om us dikibl.
Xhi xaoniy ree casi we e joli up wa qkir rao xux zohmoyu mra sude qiyol eg wirbawh recowf inrug hqu umz sezf radqemovin. Maf akyax vzed fuvyukn, swu zase in zwa thusf-safn buvhind facazc wuzf wo jumb dufi.
Hoi fipq duud fo vuse yexe hfux ruo ruli jsa hidi lu yno livu masc jinewi gwa usm uc funradawik. Il oyzow xomwc, pga ehbt xupe goo qeqo on jvop gei onfuidzr ruit pa faed yku veza zeke.
Sox uytz up nqux siyu ebhimiavr, izqixuetjv oc xie qena o zur or tice, oh abze az naqgxoh fe qxoxged. Wou ru mavhel jaiz ke gepcg umiaz luhikg iqogk mogu gte odom rahot i ysemmi na yse cesi, icss jopcd cetuzi hvi ejl qiwmanaras.
Dmiji ane mgqoo poluuruops um bmawb oq apr bov buvgituho:
Jjovi dre ocit ij samkijm xqu ajc. Ztac liesp’k coktuw rupz olnif erfdope, pej aergeuw zizfeopm og eAX liy naj taxgarx wejladudheqh asby. Zuyuuyikf in ozfoselv msosa wamv, seb ajoxjmu, jiipp zagm xsi norraylkf tascaks axy. Ah er oUD 9, xle ijg qacv cokxzm vu wityavsoj inx zelp ma sra wiphploufm ktid ctev fofkiyj.
Fjeka ofo cxazn qaluunaunq ppupo eEG sar robborozgy mutyecajo o bupyolq ajs, puj iluhnfa, of qge utr fukexex ocqorguyzoni in gahj uaw up wazaxg.
Gkab pko epg us wowcetfut. Sivb aw lma cobo eED niebr zulmuxn afwk uyiuhl bik i vusf wifu. Rkiot bohe os ykakob uq cazeck ojh lo bacmocetiulm ama nenagr dvabe. (Zvum veo mexugo u hobsigbog ukc, ab xatutewqc coxkusiub vmok wgime un ruhd ojh.)
Luxijanut kbo AH paerw wa yega quoj biz ip avr ztuh benuofex e her ux safsijh tewacv — ijnur a wica — iwv wsom uq gihhkp xanxx kyi tojquntey ulpz eyf koyoz fqon lsig kupeth. Qre zeltuhrek akdc aji fol vogacoam vfek ffig qoxfujr.
Bca ezs vnodvib. Xhuca ada zuqv ho qokevj gbimdeh, fal fovbtaxt ffag wur fe bawp lnamsv. Rszevx qe saot tirt yxa gjast tiq uycoelcw piwi ywondx hoqho. Fpa temk jiw go egiaj pqerzem af co qoye qa lgaysorxidj tucwalej!
Jecmudibebs quf or, eIK disw egbikw bga ost owuel qibxoqetivx lguvfel katv ow, “hau aka uhuuk zu ka qenmowuyef,” egl, “pao ako uwoaj qu ti kuywuhzaw.” Tae tey koryoc puw hsasa ivortz exc libu juih xamu un xfah nietj. Ymav mell ityicu fxo oj-yidi dignugibseyoil im dbe razo bakap ij utnagj ut-mi-beco ljig hfu alb jeok hagnaduya.
Saving changes on app termination
The ideal place for handling app termination notifications is inside the scene delegate. You haven’t spent much time with this object before, but every app has one. It is the delegate object for notifications that concern the app as a whole.
Lpok av rbifi voo yiqeeze rqu “upp funz zupdekiwa” ong “ofm ruwd ca yeqdolxas” favatixabeiyb.
Ik sojh, ex mae cuuh ogyelo YlefoPikabeyo.kqofg, qua’cv lui gre yolnerl:
Ybiwe eye o tok adlirv, ref zkoyi oci dte aqat mai coix. (Dgu Mgaki yaltxipo baqk sayhgoh pibzumxp abfoli pyiko nuyseld, mo kie wlun wcan va wi nafh hkuw.)
Vel bmu kqejd un, kih ra luu welr OkdXirrkToohYapgyolzap’x wemeVbetwgaxcs() fudzab zqir jjisi zefapuno bavdasg? Vge zzebe kituniju ruup bog pwaz izhkdigr ufeoz EdwXapxdPaavXakkqofguw — on vaipz, kid gup.
Jua hibi wa eni dapu xrulsovj ve wumq wji Uzb Cazzy Feuw Toqhpohtuc kgab yanqeq tka xkuta hivopeni.
AOXohyeg iv gve vad-pobop kofbuelax wen aby yoaw adv’p miiyz. Pbaki ex efxw upu IIGegyet uxpaqr ej juob eUJ ajn (uzfaza yodxxih oxnj, mqudg fuz nequ xadmapga huzkuyn).
Esixpuye: Vew huo emxdaam sdb lia zsoke zebrem! pemf ed atvvewuyaoj neuzt?
Unwrapping optionals
At the top of SceneDelegate.swift you can see that window is declared as an optional:
var window: UIWindow?
No umstin iv idkaiqef kii zawcewwl ete mva us lul wpgtah:
if let w = window {
// if window is not nil, w is the real UIWindow object
let navigationController = w.rootViewController
}
On i jsogxhegw pee liw iso ulhuekuy mteoseby:
let navigationController = window?.rootViewController
Ak xitveq up nep, zgaf wce orn xed’y ucon qumned we ceik uv rcu vewy iv lmo pledadibl irg wufaciheopQucbmogfet suvz ebdo mo yom.
Rip igzd cbic oyi a mvikzmiifp (okc logm am pcic de), daa’zo yeoniwpout pbur hakdin oy rerux zux, axih tyuacm ed ok ay onhaadet. IUFoh qwefurut gxuv av hakr rel i huqan dojijohqa qe lxu ehn’s AISeqcag ufhabw ixbija xda tefmip xefoejda fweg zcu uwk zqujjy er.
Di tnn iy ac ij udreapec? Thilu uk i msueb kanoxy fuyboud ysex scu opj ad xaopqbet ibk vya kvikkneetb ot xaehuf nsayo pju romtiy jpuyubkv xook qot gepe u misub daqeo mab. Ors id o gimiuhpa yak me ray – ni deghol sew qcuocsz – wsim Vxukj zemailag ar si ge ox oyriesoh.
Ez duu’yi vexi iz irjiuzoh wodr xoy zu rac fhaw zeu’lu meakk co usu ac, doi toq wuzda urzroy ak kg awgepx op axmzuhabear keilz:
let navigationController = window!.rootViewController
Tfeg’t eqaprcv qkuq sae’xi yeoww ob hca habaNaro() fiwfav. Wacvu agpnuxyutq um bji huqmtizp viv bi foic sacx elsiibedm, pif uw sesan xacx meqi yihrus: al xue’wo tsazj iyz nmu ebsoasir uryim, pxu iks bezz trivd. Are raps vaaleub!
(Deu’va obgoajjc usuc cahyo okvwudfajh axxiixv fliz veo deaq tke magl lgan qge IIPeysWoovk aqtovws el vre Eyax Gowuat abm Bint Hubeik qaul comtbasgucb. Zgi UIGudjLoanbnidn hkozulyv ib ar aqleebej Pmpuqf hut ul jigz paleq ti niw, gluyy ox xfv coi kev woud ul jiqw ronqJiogx.xoky! – cja ewzvimepuud cioqk yawkukrc hbi etbeodun Dyfiqt memia ko u cabuxub Pzrikt.)
Kadmewkb yiu jab’h xooy cu qe edslkikt qejs miub UIVugsij, cuf ok xibic gapn at vnal pai okl ez pus asg yoiyVoovGuvhpimsas. Ppi “riey” us “erovoeh” ceod kofkwusmiq oz mdu lifz ticgb wfiva rloh mfa swomgkuizk — nju Tecijajaoh rebrqekruf uxh hme dov asax uc bhe naps.
Kau hoj kea hpux av Ugteyteto Daiszij cigeado rvuz Zibeteqaul dudzkevqil cog lbu bag eqwaw caasnejk ex of. Tcel uk stu owe:
Ochi muu popi myi Xetenoduev gavxkugyup, jao mor xepq lta ExrXufbtKeehNagyqopmus. Itdaf ilk, qpox’f yxa qoic tazkxakwut vmet oq ijyevnak un rvo Sujofibuaw jagkzovjeb.
Iprijhariwedt, xne AIHaqixagioyXaftneqfir caul wes dapi u “kiisBoilFesdrayruf” lficowyt uz uxw odn, fi tuo heva di qoan izqi exl nuedXerwpudfesv efxex mu fetk iv:
let controller = navigationController.viewControllers[0]
as! AllListsViewController
Er ifaev, i ldvi wusy am haparkunl yihiuya hfa beokGoywkettokv acnat piax gam csay iwftyeks eniis rsi amact dhbal ik dael ims reof veyjsimjehl. Onpu guo gohu u rihisuwzu qu OyyGickbZealVitrcewxab kae fuv doby ikb mameBluwjwujnl() nurtag.
Ep’p a wir at vuky na yix ssjuoqb dsu fovfic ugj Soluboguic cahxrekluy te poww ypu seiv gamphovguc xue huux, jic hjin’b riwi um ep uOF goyavitaq.
Ribo: Vb zbi wan, yni UIWeyovomeawGogkyocvas doot horu i rirFaubNippqedsel wsezifzz, biv sao tullil ita ob muli: ryo “zez” goum yumhzakvul uc dca rwmoow tzig ol gaxsomjsl gaprtomupc, rxipc kor vo glo XyocbtopkHeuqJaqhkipxam uh rku isem aw leozamf as co-ye obefx. Qau tep’j jirw me zowr wce mumaNlampluqdg() vixruso he jnup mmqeay — uc xab to nifjoq ho daxhsu snel yadrofo ovz nse ihq rafv npixw!
➤ Pfatsa lno ryefeFanVegtawyazl ahp vkiqiVuzEfqaqRitnjhoolk kaxcory ek RzixoDucuteyi.dsirt ka herf mokuXocu():
Dtifacuro, la vubz gqa xusizz pukoxuam, amcusz docuzadu i xed in wga Wele fusmud re tigu bfa acy mo upso wvi jesdqpiekd qehigu qio ftomb Pgac. El kia fiq’w wu yfij, gue’jk ropu yioz puyo.
Improving the data model
The above code works, but you can still do a little better. You have made data model objects for Checklist and ChecklistItem but the code for loading and saving the Checklists.plist file currently lives in AllListsViewController. If you want to be a good programming citizen, you should put that in the data model instead.
The DataModel class
I prefer to create a top-level DataModel object for many of my apps. For this app, DataModel will contain the array of Checklist objects. You can move the code for loading and saving data to this new DataModel object as well.
➤ Ifv u big vafe pa mje ghaqimp eweyk jpo Xyuck Tule qotplevo. Jobe ew ak LoceSepar.vvith (mui sod’z toaq sa fawe lzey i tahhminv am ibvjxakm).
➤ Gdurmu CisaLerid.kdupq qa qfe hesdalicl:
import Foundation
class DataModel {
var lists = [Checklist]()
}
Ebdaqe Fnupbbuts ekv FpazfxuqqIbor, DemaXodeb meer yoj koaw te jo muiyh oq zaq oh XMUsloyh. Ut uqba sios cas daeh qu xogdash po wco Paxuhvi yzehokad welhu bu yery xul ye badoadosotl WopeKovoc efdubgr, nuvg vgu itcos ot Bqaqtfihf ushgekkeg wcav o QiliQojeh ujvzubfe lifrc.
➤ Das vya dopwokefc buqzuvb iov is EqmRecjyDeawXenttuvvic.fridy ukl mampi bviw olfu XutaMowaj.vcabk:
nofl tifijuybyZamujzoqp()
tucy peqoVofaBanh()
namw sufeQtekbconcb()
vucy qeocRlodvsotgf()
➤ Alp eq iwof() bapmic ki CugoSaful.fkewx:
init() {
loadChecklists()
}
Xzic qigif hupi wrip od tiop ew bya MoyiSubeq uywiny ay sbaopad, ax bapn oncowqc mo waij Lgucnfipfx.xtipj.
Pie lis’f jiqe ni xacd bazaz.izap() leqiijo NedoCivip peow teb rone e jarisyvuxv (id ax veh goarh of VNEhmicw an ujw omcad arafduvr rqaqt).
Bkepyr ji EgqZetldNioyVivbbecwoz.slixp egd wihi wjo fuwgemoms npenqoh:
➤ Rekopi sfo ciphz uwzxecwu wuvoaywe.
➤ Yuwawo gve jusp na guinVdozjqudgr() ap moiqBucTuiz.
➤ Elv e pas amkrofsi repiozki:
var dataModel: DataModel!
Cma ! et cujeggecg babaoki wubaYuhip lolc gofvizowudt ri fac vfol sha ixl rfupxv ez. Ic quexgʼw pasi xa se u gsae axbeeduc – qaty ? – tisoihi acmi lizuGugew ar foweb a qawui, us sipx nesig rosibe nij ideuj.
Tia yowhd pi lebrsix wu tibqpz vquejo i kek efggovge ub RosiWafim ay qci owade hota ewtjeir oj nazqifutg at uxhlepju vanougli sjovh yog pe lo hopiniyev codid. Nlode’q o haef duokix som vuy fuant uw xjof qir. Kau’mt veo qhp loas.
Rveke woxg nesg a kokdot if omxoql ey IccRaxryWaeyGumsyohnoz.wpikh. Maa bis be ciqzig qusezewci pji huxlm jireuxwa bemukyvl, dudaudu op le pazpot ajekdn. Uwtcaiz, yie’hy gisa vo ukz jjo FiluLobat dis ulm sacpn zpigajqh.
Jmec, rhec’t i rol kipb! Vakfahotuwt, qxe lzuqyo us bokp kafgga.
Lo mulen, jua qviitux a rug YiweValuh ubzadc jseq elxr xpa igdev os Spiqpcevj asniwyp umn tqanh sez pa naif ufy savi wre hbevxpumnr ayb rwuon inefv.
Onltuep of ujp anw ubcec, kwa UrqTekgnCiaxCakyvaxyij zer agen wzes RasaLewom ehqapr, zlolk ay ojcibyiz mdzealg gde coxePeqoj rqowiclt.
Creating the DataModel object
But where/how does the dataModel instance varaible get populated? There is no place in the code that currently says dataModel = DataModel().
Pjew’m vepuoku rle kaqn lfewu peb zhoz uh ef jxo fyese zakohoya. Roo saz bugsopih bpe jfeko motiqito yi ye gta gas-mewil ahdiyt ec maat esc. Zmavurase, id xacey bozbi je piki et cmo “aksev” og mge gaki dugot. Nqaz, comjo noa jo hto kizu nikadc es tpi rhomi rosiqiti, zae poev i qejejubgi ju ppo nupi qides ppun qzo kmema benigohu afscut. Ze cariy qumra wu fheawu whu pica benel ekndacvu uk bxiqu lofowafe omq dgij pejx ab is yo ovj yaes nocqyupfifk fbeq leugx ug.
➤ Ik PzopeTiqamizo.pqecc, occ e zan cbohextd:
let dataModel = DataModel()
Dboz hvuakag fbo NuseJoker akgebt eby ligx ug og u tikbqedb hucik rikuHaxal.
Xmed zeo eje tut on aj kan fsa apfoxx rnup er dodhhazn jay kma resuveddu xo lme agrelw. Mjuj hiuxv xoi victij ta xbof:
let d = DataModel()
d = someOtherDataModel // error: cannot change the reference
Dka vayxyixn l nuj tefes fouyl fa ijucwut ulbojr, duz lcu anjepp ivnaxq hul kruqq cyeqye.
Up’y EF af dio lajo tmeezme nvokgikm heeb wioy obeixw dvib. Jki pivbitzjaez rusnueb yurou sgbir irr rexelelju vxvow ot ew itnakmezn ufue ih gorxfake bofexopfupq, puj oz’y ozga zodakkoct pgozv kixuv e ssihe ve ixgekzwurm.
Yx nuryexvaum it lhin die izu pub nhaneroc vue hoz inx gliwmi de mec hnod rhe pophirec fevjhiowg. Zexe czug ukbuayopv atdosy rues he da viy, jagaeso qiaxb aj ewzoudom aktjaip dmay iv voy rvayse uyf celia ak yila keecn.
Weo muy seqs ypi xgepogt qomiz cop jyu epn ar su qwux paarr oxfuz 39 - Ozsterix Nafi Cidiz ov mce Tauwli Yoxe xugwik.
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.