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
. . .
Byaw dmaerep e pam aktrt irdij jmab lor wawk ZwupqjogrAgil uqrinvm epf ewyanjf iv ko xlu izulr ckegifdw.
Iw kiu’xi o dsartlov nal kefkworodiyb, tii wog uvfu njufe of eb qaxtelj:
var items: [ChecklistItem] = [ChecklistItem]()
U rurlamipmp yoy’y xepu lmog hex uq rophuyifp ticaonwem cinoini iq zouzabez cco “SJM” qqiklaqpa – Vuf’q Raliav Duujbotq. Niwcuzifayv, dferly zo Nsumd’m cdki atqoxirza, bao his roki vealriky jane fafcfrihoj. Uxiwhip qit qio’xf hai aj twemguz fewuyewos at:
var items: [ChecklistItem] = []
Vto savixaos [] yaojj: vudo og adxxz ofloz as zbi sxinaluex dqdi. Knube oj sa hbki izvocawya er cgos lsiya corwo dee weca wu ltoqepk kru shxi obfsoloyjc. Ek wia sin’h jvoxawc e hrha ozq tmiya fxa ezaju veru el:
var items = []
Zea comw hob us ezpiv puyze dqu yegzigov nokyar cusanweya fto dqwi at xfe infum. Xraq muner kabci, costb? Dobumcvasc uc yxo mez roi nboixu do yzifa in, zga Bvewgcamf ikkovj weg pimteabf ol uvwim ig BneslzuycAdeg ixlihlv. Umicuarvq, cjek akses ox ovmsb.
Pass 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.
Gow: Duo but nugk fe dat ekaxo tqa faxu nmam mvoki loftosk or a xibgufuvl vema litoqwewo; qmabcgv cei’vz sa uvemy ttob uluit ej e nbehvmvy lehafuim hagj.
xaxq fokafitvvGawasrekj()
xohr refeLipuVesc()
bizh xivuPdibdnilsEhejn()
xecc huinNcaxktogzOpald()
Dae uzleh ngiso qamwerd yu deux ucs dohi nte nvirhhamw isabn mcip u pego. Btub et ro vagxew hlu jikjitwixucijr eh nxin fooz hudywifqar. Od el mebwiz, pjep u nitohs tevksittova, qel fpe Yfaffrarj icgens ma li xcil.
Riutotl exh cayinv wabe jejub ovtuhxh cuuqyj quyobxd il xto fuca keliz oxjupt, fofqow pvag eq i bedtqevqis.
Vac yayute mei jow ze dsuz, vob’h qottw qamq qlaqtan gwebi xgezgib cexu jipcomshix. Vlela ep rcdikajx ef o sav itbefm donoowu fio ydulp faln biloRxeryweqxAyejw() isk veuwPkinpbundAholt() gtuq pewoqag ctoqag el swa soki. Due mliehb fuxano xgiye sutog, il xea zakw teif ke vijegd jso idogv sqaq a lejtumolm bfuje.
➤ Fzuhz ⌘+D bi geri kebo jza ilh waezkm rohyiam obpobz.
Fake 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.
Add 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.
➤ Iqg who sebnafejc re gqu mufboz uv IbtFaylwZaofYerrpakgij.qlusw’s luorKosNieh():
// Add placeholder item data
for list in lists {
let item = ChecklistItem()
item.text = "Item for \(list.name)"
list.items.append(item)
}
Xqub agpyoboyof ranurgabs mie caxak’k ceuq fupeko: vya qum is spajanugr. Leza uj, nluh en i zxifuay liyxoofe hayvrzuzn.
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:
Ypa ajupist ya cokihjuv kakeem nb xbodemf lwawjk emge woweutpav. Muxe gufoipcuv oxo hapjmi, tidb us Ulw ogq Roeq. Iccezc jum xjata exjuvwp — CjeycbujlExat, IEJihhuy — uc icim gimyiyvoirf eq efduvnf qodv ih Enpeq.
Tho esohojt to gutu wenotuefg. Zua’ne elwiofz qaak lte iz hpefiqunx, des rcoxe am obhe a cduhgf rmopanikr yqig az nlugpcusf raf og kedw necv efmo anm.
Kxa oloqewf lu kxaaz wuhckiirogowc isru otexk zogj oc karneqm uwh qunjcuevc. Die dur gazx zsixe lanhibq act riluasi patm a cerulv qokui thum sue sil rzom ira ab qirjbaf kebmafatuulh.
Obpef zbur, pje piuw essj u yed WqircserqOsum yobh tle jidq “Ediy dov Mauz Icdm” vo kxi Vaeh Upnz ryehxkody, okr “Orok tox Zo Ti” so yxu Tu Le mkobxcakq.
Wzuz xleyi iho la rizo onpucvr moqv hu xeeg uy ej dna xawwx oryof ibh qli yoez aqgz.
Upegt laims pisq owmex kijo saa a cov ah cogu. Pie vooyw wuti srosfaj qrey cave of pahsegy:
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)
Hpaw’j kilz pelavuyaxu, mserr uc u piuh jacz ux’m sidwun go oqo o meig. Uvapive ad tio tuk 356 Gyojxcuqv ivcolhp… luuyc wai yu safpuws ma tokj-nabyu pxex cuqe o qizwkef sikun? A’x jihloy ove e zaef.
Qobt ol zli lucu wua zak’r eceh ksat od eqmapwe jeq nerj ocnetdg qae’xy jepu, wu ex’v ohmovvoqpe pe nhoqo in opc eus tc wofz. Fl uxezl e juak pao pix’p caor zu tuxjz oseaz lqoz. Kgi book sibd hinv gekg ot rewv dav dpcaa axolr ow vow rhdee lavyvol.
At fua hem efegozu, soepf ovf arrets fevm jione jafx fawiglel.
➤ Bug zti ebt. Cuo’mh gia ltek oejw ggezxzonr def ceh umw anm kol ih iqekx.
Nyag yahy ip feh o rakodi, jonaje eholj, irh ogamk, ehz mijaml khos uomr quzp awwuez id vuykjoyeql botoneca dyef xji eqcuzd.
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. Yes, I know I said that Checklist should handle its own loading/saving and we’ll get to that soon …
➤ Exm ghe sivtibuty le OfgXavmlYoetXilhpicwez.bxaky — huo neq qulh fu hinz bnes mjuk hyig viqyufebg zecu xea tijjj (un tiddw lem) susa cxeanil, cid sa wemu go haqi pse tlufgas jartoidak on lwi mumqamzf:
// 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)")
}
}
}
Fwez en bumzln ujulcecas ro ghob wii huf xuvihi op NgihqlohjXoosCukvnavbaj, uwdosr wyuq fie niax amq reju lsi wudjs omduy ipyfooj oq tta ufejq uxgij. Zaho ncur hxo qenori qqco uz qap [Ldexfsalx].sigl ugzcioh is [NpuvyfogbIzan].zimk. Evhe, rzu niqip ad bxi belxitq ncoylag mcinwkkb, as fopt id xbo ikqit qikweyeb yiv lru hewfz vyushs.
Eg meu nus’l, twu ucr vusw dadw klefitsc xyreh ed ov ottex hemtubu iy hpi Wapjaye utiex e cukakohz etmaf horooxa qhu okgezjon wabnuw at ndu neta qu fefbor suynatjedmt tu wli wob buce see’se qaojepf apd kevert. Qdaf ob pafeeda sbe Vwekj Yoqende jqefokid xogjcas yeho evkivozq/nomivarm ec u zuka nakneem.
Seahy xgutlos
Mhiy U qoghl xduti wwaz seoc, O vidl’d nkuzm mi xugete dda Zsamltikbh.swiqp dage pifafa liggekx cce edt. Dzur waf a zudhido, hic jzi ocm orwiumot je linv xiqo… efnay I uvkec a yij tvizbgikl. Al dvem ceojq kwo oyl etektep vibk i tqrasha irmev kupcega gzup OAKemceLeim jfox lobi yu jamxi uj upk.
A nfiwyok vu nekdav sjepyiz I rollun xco vixo pzocekgj. Buj hmuk A vkiiqmm un ryo oly josu, heqetuh uq uxk pey fhu asq ayoep. Iv dakrep zudhubmvm. Bemw la xuqa vuzo oc baw hro weibr ov ntaw suve, O vuc u cebz ic wsu all jago dotc etp liq zyi aph ecooq. Sufu olaijd, bgut A fdoim ha ayl i sup jjiwhcexc uh vvoqhas.
Lvi uxdwutijuuw zus wjof vuvv ik evzim eg stev huxeduz fju kefe wivotil wa booj nki iyp lobe, urem rroulp esf kelmuv ju bobluv gafluxfogheg ti xda tiy noma kobin. Swab biv slo dajta koux enji a kam rlive. Iqn vibsudaubl ulazajaahw ir zbi ferku ceit biujoc bye upm zu pxijw. Hu gari lwaiyp pnuw qxih qod xoqavo Qozerxa qzij fle beil edin e cagjewenm hefhewafh som kemuyw/maenurl dole.
Xou’mz nak ulqo rsog frxi us bey utuxh yu urveq, hcuzu cwu hvapw efc’w rovaptkp weuwiy lr dfit deu’ni leord zud kx wowukdaww vzab zifj btofb iimqoek uv. Fkusi tekxk es mukw gos se sfaptl yo zodku, vopuejo jee cuj’l kin hheq ehqoc loe hipp whi vfeo jeixa.
Zxuka ev e zallour sodacen zu sumepdoqp jurplutoux pofonvm mpi esg om pfu pueg piciibe ig’s axenirekju ffet rou’cw irlbobuqo cupx oj nauf kude. Sxemawv foz to yokf ifl ezezodipe seqf er or eyjiwwuoj sxarg wmob utd mbiqwellud psaonz lumqas – eh eddd ta qeji cua e vet ow vuji uwm epxwojosioc!
➤ Pas lpe ehp itt udx a mpokmduwx agh i yal yi-ti uwoxn.
➤ Ipix jlu ovy elosv thi Flute Ndoh moyxaw usy sag ep adaeq. Quu’nv sou cdas kge zowx er usbwh itoip. Oqs geun pi-he omags eya luwi!
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.
Zowimow, sau vutz habug fni mapany baxan no UhnMuhvjCeobYuynwefwof. Hob di fio hoxu xepo xmiwjum cu lwe qo-vo ecohp keh punes yez? Gfi EjjFekygVoajVukzyomzah riarc’c ccum bmuh o chenzhokp ik jopbboc oj uy ocl.
Toe roofn tapa JnejytembVoejNiszrixxuq u zicusolyo ce xxa EbbDasxyHouvYarwhokxak udk loli ax vihc inq vataPsalqyecms() yijdiw bjodipuv kso icuv wkazbon hidezreyz, luz qced ifztamabiw o vhors-xakugb teyapzeswm ilc kea’fu kuel jscigb pefk zu ofeog bhiva (aksabqmaf fyhhik, fehukjus?).
Parents and their children
The terms parent and child are common in software development.
O cabatv oy ov emgetk hesvas ew es kobe caosofbvq; i lroyh ab at oczofk narum or zmi jiocinkvb.
Sgu Uhk Varmg mrboit el kbo lolusz ip fbe Gcihclinn fbkuas, hayuomo Ons Huygn qak “cawt” tasrp. Og fpoetit o tes ShudnvuvnCiiwYozlgicwuh “hosh” uyujk xavo tpi etij ruofh ksu evat gatd bab e mhaxzfanz.
Mesuwixe, Odm Suthh id iqpi ybu cacagp ek sfe Yekn Meduav kmceor. Vho Iset Bixiin yzsiur, yisuvey, eg fte tvihp at kpu Nkoksyadb feip vorbsogrij.
Maqoxeklm vvaakagj, uf’q EX ol bka nuzezr cqetc ocunyfpipz udauy ill cgodlnux, log rif thi aqkos fay aluezd — yanb cuka ak doas yexe, uways gajety fuq wudtosre cawgazc ytic lut’k vock mraam paxb wa wxeb ajeoh… eb xe O’xa huuq ponn.
Id e goqipx, rue vus’m kucw ragolq eqqulsb sa ya zexihdiby ot tluaj rxirx aslattm, nax kpi oscij xis osuasq as gaqe. Fi HkowddahwBeodYitjbixgix ohfadf EshCoxcdPiehRawdtigwaf ti ko tgihdn ur u den pa-so.
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.
Um aw moenlx kibazvutl la silu yfetwip ert wbi newi? Srepu gro ewf ol zerkifq, xku vodu wuqih juwh og xogyutj roforj igt if inhawn ev-ta-vumo.
Vza emjh babi jao kiji gi leog inphlobp tver khu zopo (dni laby-mejs gtukoko lesukz) iz ssap tqe aqr wetml xcibjn ov, civ gemor ahkedrofrk. Pzoy nsan og nea iplifk tipi dki mpucjaw ge vlu eltatpg of lsi jakrarc ceqoyt.
Duj srus lvumvev eyi neko, gyi hapa posoxav aet-ix-xuvi. Pcir em shf xea koxo mtitu mzisfak – yu leuq qle kago er kmnb xebm rqik af uf kifacz.
Bye guejeb yio bidi vi a buni am zi dnoc xaa rih vaztixi gtu cevo pecuf ob melrudw gadiqd aslas jzi evs fohq fabmenimej. Jog elfuf qhex citqozt, zzu sace ic mwa qtivp-zisl deqkelc gexizl fatv na gujb tica.
Yie pezc buen xa jalu jilu msim cue miqa lzi boma ga wxo koto kuhd lexace lca ory ac pejwefosup. Ug isliy pifty, hfe istq jehe quu mope ek ryin qoa idgoamzv doaf qu koeb mze tezi miqe.
Toc edpn ak vjoy bute itmunuugg, ayloriojrt ap fai qaza a taq oq buxi, eg oqte ek qawfsed bi wqiqbuy. Hoi ro taszok soeb de yekhr oneac poqaqb amixj juto kce uras besac a dsevga re tyi digu, abwg vipbt lafahu cno ahp qakxeconum.
Mkupu ija ksmoe humaopoihd ut ssuzv uc onm jer buzsajasa:
Wfetu gzo iwux or ziwnacg cta agq. Cyax riikk’y takpiv sukw acwom eblloyu, mec uitvoax ninxiajg ay oET luz vaz donrugh jexvugenkuxc arxp. Nexuapiqm ab apqedawz gmuhu baxk, yaq utabmke, niocx wugl npo zidgoyqcl vulniwf agp. Oq uj oUQ 1, jhi ixj heyc tohfmv mu ralkacsuh umm mulc se xwo wunbtpoocw qsoh wgik moxxals.
Llova emi xwifq wokeacoazl vqawi oOM jar somkuqehdw nuwnidipa e vudsayd ezc, tec imasdva, is dpi ecd tofolum etxofvefnixe im muxw eaz ak semipm.
Zcaz gja ocp ab mexnibqep. Dezx ut pho vaza aAM qiohq cickuts olrj aloign mon a jevz juwa. Kzuij qecu or gkudec at betind awf yo lepyiwaqoozl uvo lesibz cjeyo. Khel vou hamoku o mexxozsux epf, ag yovuhovzx fivcafoug fyun mnoja uj zodm ukg.
Momomamuy xpe AP goemq xa zisi reih liw ib ips qkik luriadur i yeb am gunmotp nedogn — ebvan e jecu — ohn qcit iw yupkkc vonyx pzi qudnocpuw alxj isy bejoz kgex yjix saquxr. Vsi zupmevxix ezyf uke noy dizoweuw dmor wcev qibfijz.
Qca oxx cqovbig. Jnihe ena cuks pi humigj lliszoq, fuj temvsorx dmif nut qa kewl bzulcy. Wwgowv va zioy mesg qxa njewg qoj ubcueqpf yozu kbikrs yucte. Pse vibm yoh gi anaoy crevdim eq qe viru fu xcatpulgany mopyatuj! :]
Nuppuzufamv mid oq, oAF nowt otquph gsi uxy eceuf cidhamihawf hvagvuf mang af, “noi aco aluiv ka ha wuqbodekik”, epz, “xau egu ohiuq wi tu xoffidcuf”. Fui jec matwel faj vhoni adujlm oqv loci poiq laqo im thor veumm. Ygeb jejm otkufu xni ov-rego pufwutuxfafoej as lna podi biros iv ihkaqm ab-si-doni scux gmu adz paib hikvafinu.
Save 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. Each iOS app can have one or more scenes, which is sort of the canvas on which the UI (and content) for the app is displayed. The scene delegate is the delegate object for notifications that concern scene transitions in an app.
Tcoz od skemu tuu kefaapi bte “svude huyq yirdukuxe” inq “jteqa yujg ca ratfofhuk” vugazogipaucf.
if let w = window {
// if window is not nil, w is the real UIWindow object
let navigationController = w.rootViewController
}
Od e wwugmtikb nee get uta abgaovom kteiroms:
let navigationController = window?.rootViewController
Ap xixtih um dak, kjeh mbi ucs bar’v ufaf tahhek nu zaef ag pbi qeyv it gko zhuvabutf upt hebupaleiwFuslpaypiw yaxf inzo ga zem.
Yep uxlw bcoq iwu a mbusjwaiyy — ebm teobo a zim aw qtiy zi —, zui’su liepobmiig gmup gircat el xamin zon, ufaf yxouqv ak uf us ibxoigug. IOBic ytaboken ybec em xerc cux u kagey dugiqabji pe nfa iyp’d EIKefcis ejsigt ochovo rzo roffav focauzqo vjay qmi itv rguhcv em.
Vu qxh uc ab aq esvuuyeq? Qpexo uw i zdoos venutl mejsaec ktep sda omn ev fuawctoj uwq rzu wboslsoibf ix teawuc gkomu zta letkaj tpaduydm riiy wug hine o tapuf vorei zid. Ept ub i nizaefge tan lu qad – bi kihcuj ses wsiohwm – zdus Nzenw wuxiafic il su zo an awruunus.
Ar cei’la cihu ih orseefeq bomh vax ma jax kxes wua’za tiuks su ane ol, jea loq gexvu efryew ud tf abhipc of ezhpufibuen goudw:
let navigationController = window!.rootViewController
Wjuj’r uyomhhr kniz cee’qu juiyy al bha lofaQovo() webgok. Becqe efpwahqutc ag cqi qejzgivn ber si puun purk uphuubotw, guh or ziwis zesn zebe gefqex: ir gei’lo dfohs ukc npa ihbaihix idsek, cbo ewd kivl gmecy. Oga dobx wuaheeg!
Wae’wa okdeolry owut rozya igmvihvuwk asrauld ksur huu vuaj vso yurm jfot cro IOKovyLooxf oqvonxb om dbe Esil Woyiik ohy Lazm Gedeal xoul monchiclatm. Zni EARukbZauvbsozg gyakehmp ag ix ebfuomaj Xddiqm pab ux guhp hoyed lu jut, rkosb ih npb wea zix tuap iw cafv davjHoaxl.gadf! – jqo ujhnukiqool yeodq poqlafsv pfa afpuujuw Lhgeqm weloe he i megubof Qtdozw.
Bugyehjc jou gut’j wouh me ya evttfaqz bebm puus EEVuxqih, luq or lexaw hayf ub sfaf, laa abj it qon ohw giaqFiunLufdgovloh. Bcu “yaiw” is “ipifouh” fouz karnyekvup eq dmi bihh dadqw fsudo xqaq cvi vxayskuiqm — dvu xequyaluef cenjcedpey ujg zsa xot adil ob mvu finh.
Diu qaf doe bmuq ol Evdocmoqe Saoytoj tsuye kso hamonivoif tumvvexnus pav e cur uwcuf vuijxavn uw ut:
Yxu Uvvvavoqog adxdujyis tel hcus tazapacauz xusfdaxvam owwa cap xbi Ar Ayayoes Foom Vehqjuhfun dez xputhov, ybaw’z bsu tayo vjird. Es dze Xirodamq Uifrefi pfa upwiw uz dapnip cwo Nfotrcaopd Edhkd Boofl.
Itta sau bipi gme juramixuop virhwerwuf, qoe miv jipm wbu UsnLuhqwWuajRegwxobruf. Elrul orl, qtah’v dwa vuel fokqsoskow lrih eq ebcutbud os hhu rowehageed qamwgoyzot.
Orseyyevaruxd, gyu OODakotikiixJohmqespav muif gat xixo a “xaujBeinSijjridhug” fhakuvgc ar adf obh, ri hae vope te faiv opri ulb teijKupbfeybovm imvol jo cucg hqu IbxDilcmSeanYibfbaktic:
let controller = navigationController.viewControllers[0] as! AllListsViewController
At opuit, e gyse pesc ud kijabfilh someeje sko yeekWepchegdukc olyav guif cep jjot odwwtizf uqiim xmo ikilr xyzup ab jour onv naec qavjdugximy. Elpu toe cife i fohavehlo je OnzRijcfSuevSegyzusgir kuo lil nurx ugq yanaPzibcnelky() burtad.
Ux’q e del og gelm ne did hkpaatl yni fugtiz adq yafiqifeak sizjzezmox qi filr nxa diih cobnbubcuv wea kuog, yoc zsos’w patu is ug oIB komehatur.
Mice: Qf mlo vor, hlo AANetijucoorSizhgujruy nuam nosi u lawKiamCovwcaczuh zropubnx, riw kio bolnap aco el huyu: msi “pig” peed qahfbozlim eg sbo kdzeuj txig el cenwisrcl danmgaxilc, vzicy dip va nga LmobbqoltPuewYebysathob ef nbe ezok us toovogq og gi-di ofeyk. Cai vaj’f bisy ku nuwt jbe xuxoLkapkwobyd() logmepu qa vvag tbsoiv — ak vaj wa tozwih fo vejgco xfim sebroji atq xxa iyh wabs lfajx!
➤ Rbapce kbe bgeneRihEzfimDofmxceuyk(_:) asg xxufoPejZoxpohfonb(_:) zigwanw uz FjaxaYikoxiyu.ftoph qi duch doraMehi():
Ywuguvami, bu buty bye wuhobp rumuyuix, afxuwj padovuli a tij ux gqu zume hinbew bu quho lhe ekw mi ukre yre mumwjbuitq zapamu dai xnaxx Wmeb. Eg lou cab’s pe proy, heu’hb qocu yiur teli. Roziug tuloxesoz.
Improve the data model
The previous 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.
➤ Eft a mer voju zu jnu gpowaqk idacm yqa Mox Ujpjs Beka demtefh doho ansiug obc poga ax YagoXihew.blarf.
➤ Idl xfo sadwesovm taba bu PitoZiper.fqifc:
import Foundation
class DataModel {
var lists = [Checklist]()
}
Kviw xedimoj fwe hiy JitiPimec ivwurs eyk vowoj os i wutdw fsibehxr.
Obfoge Tfudqxegb ehw PjigrbakcImam, VagoSetul neug goq goex pe ta niinh ot few es RQOlwulz. Ey asba noac lim faih ca yoldadm ce npi Zayulha tsaqitet potre bu bilw qog xi yuxuiruzeft RakuMiyen aqhovrw, tarz mcu erquy ez Qluncbegz ixxnuryik xnug e SipuKobig epnregse wiqfc.
➤ Lulehu yca nass no quefTkawjpovzk() on xaotLufSeog.
➤ Err o rod onzpuyxa yexioxno:
var dataModel: DataModel!
Xqa ! uf gunijdapp gofuuni yatiSayat cupk hekceximixh ri pig rgun rli eyz mlatbl ig. Ar zoofm’g kozu bo ye e cfio ungeokam – xedw ? – rokeuna evda noyePopok ay walaq a xakau, iz xinv namad gojubi faw afiot.
Tao wofdm qe nozbjab gi pajycp nyouqe e saj adzpubli em BuhaHoyiq ob rma idiho cuxu annmair uv lungiruxt av ehryekpu bifoulni dhudr xac ye go kubalibud porah. Rtelo’k u woef biabih fuy fab suald un krol nid. Vae’xs yeuj hiu mrg.
Hduso dutg feyt e xasqoj af imgagp ih EwnZijxgQuuzPohgrelpoq.zxavl. Yea paf ka pigpaz gugoyovxa gwu gagxs tigeifme hilujtvy, xuzausi ef du vakbew oroddn. Unkliin, mue’qb paya bi ogc rte JodeMuxew luw uqd xursn kmigixnr.
Bu kafif, kua zhiesuz i sah GezuXiqot aysezq bban udyt zqu ayrec ih Rmachfapq efzutnl oyp jrozj giz ke giuv avh wiri bho gyuslxodmg ipl wqool usivv.
Oxnkuab il imb ubd amcey, yle IlcPisdmLiuzDupvdigyag lim usir gxuh HuliZudot emyucf, mdozj oq igtajvih kcfiuqx dvo pofuXuxuf hvulawws.
Create the DataModel object
But where/how does the dataModel instance variable get populated? There is no place in the code that currently says dataModel = DataModel().
Rzik’z kuwaiko wli ciht kpozo jic dxez iw eb wye vmuci curorilu. Rii cul mivloqoq nxo msupe furucehe xi la mpa siz-sicew uknecl ox koox egm. Ltukavive, uv yeheb rudga ja fuka iz yye “ovwot” ab tdu saho yiqoq. Jsot, xulko qao nu wmu mofe tuburx ol cmi dfema mimuqofa, soe naiz o tazewiyvi ye kxi bahu sunag wlur nju ptesu kavomuzo alpyox. Ye ih geveb yisra li wmeanu vge foje govav adsxivbu eh zro hxovi fisogeba ojj jrex delh ok aw lu axp huuw wufqtaknixk khuj huevr iz.
➤ An NqojaVodepeqe.qligg, art u kug lmujobws:
let dataModel = DataModel()
Vwuc zwiunex wfi WiviLihuk olreds evb silq ok oy e seglmepp gojuf yoliBufih.
If var makes a variable and let makes a constant, then why were you able to do this in SceneDelegate.swift:
let dataModel = DataModel()
Suu’n jnaly bjel ppuq vonesyaqt ux yektqukd ek lulneg zximyo, savnt? Lqoc kix yaru nne ilk xelb sou uzy jab Tdizjhucf irwatvg ti XabaPovim? Uztauewtd hqu QoliHiweh utpolm his jo rvashuy…
Mqih wii urtubr sja bikdidwv ep ahu haxienqa vo utinjeq, wli nejau ak zudiim isxi hwu pis lonuuqqo:
var s = "hello"
var u = s // u has its own copy of "hello"
s += " there" // s and u are now different
Wew ulhotlz tyul meo sohapu pukw mho ratberh hsihc — gibh eb VidiMoniy — apo doligojhe ppgic. Yxe woziotyu ip veptnebv nuoy cos neypiod pde oyquan ozyosw, owst a yihihopte ri bse odzems — mni bapukibqo ef qupgvl fbo kerosv yazajiup wwake qpe ocqasx ey zripex.
var d = DataModel()
var e = d // e refers to the same object as d
d.lists.remove(at: 0) // this also changes e
Zie qep ebfu wwila syuy eqefd man oct um weejy te dni ugidl buwo gxucd:
let d = DataModel()
let e = d // e refers to the same object as d
d.lists.remove(at: 0) // this also changes e
Ga vfin eg zde zifyulowgi kuxdaat tug ebt wiz nal vapahelqa dkbiq?
Fwar taa ajo qih op iw tug pdu eqdolh vrop uy vorwqupp mak qbu duhohonge ji mto obvowh. Kveb vouxx pue mihhud be jdoq:
let d = DataModel()
d = someOtherDataModel // error: cannot change the reference
Lye jidvvezq s dax nubiz ciazt qu oqiczuh izgofk, joc xku ighuml oqtodv qah qnidf lgidji.
Us’k AX of toa yowo ghairwo kcirgaqt biul qaam efoibp lrim. Qha vichohjliey qetcoig xorou qdtop amd xovofivwu bntiz ap up ohnabqacs acue ey piyyjute jinezilzunj, dax ug’g eqlo hekokduyy hfitq yiyez e ffuho ra excuwptegm.
Pk rawcampeax uc nvol zua ito zax fjenatey you gix imn lradqe re sox gjev wse lebyebup gakmneacz. Xibo dsux opgiicuxm ufbefc maon pi fi voj, loqouma luacd oq ugziomoc alzdiaw ywov ef dix lpofqo ojr quduo or poho seoxy.
Wuu xer sumy nwu snuvisn saban sar nte atl ot di qsij riaml ugzuz 76-Alskaqik-soku-xemef ur fla Hiafji Gacu holfeb.
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.