In the previous chapter, you designed and built the interface for users to select a movie and read its details.
Now, you’ll move on to adding more features to the table itself. You’ll create a toolbar with a search field and you’ll make the table columns sortable.
You’ve already given users the ability to mark their favorite movies, but this data doesn’t persist between app launches. In order to store the favorites settings, you’ll learn how to save the data and reload it. This involves interacting with the Mac sandbox.
Adding a Search Field
With over 28,000 movies in the table, scrolling to find the one you want isn’t easy. So it’s time to add search. The appropriate place for a search field is in the window’s toolbar, and that’s where you’ll add it.
Open Xcode with your project from the previous chapter or use the starter project from the downloads for this chapter.
Open Main.storyboard to set up the toolbar. You might expect to add it to ViewController since that’s where you’ll use it, but a toolbar is part of a window, so you add it to the window.
Scroll the display so you can see the window with the Movies title. Press Shift-Command-L to open the Library and search for toolbar, then drag a Toolbar into the window:
The default toolbar.
By default, the toolbar has three items (apart from spacers) and you don’t want any of them. Double-click anywhere in the toolbar to open its editor:
The toolbar editor
One at a time, select Colors, Fonts and Print and press Delete. Next, open the library again and search for search. :]
Drag a Search Toolbar Item into the toolbar and then drag it from the toolbar, down into the Default Toolbar Items box:
Adding the search item.
It ends up appearing twice, once in the allowed items box and once in the default items box. Click Done.
This adds the user interface, but it won’t do anything until you write the code to detect any search input and filter the movies.
Processing Search Input
The search field is in the window, but you want its data in the view controller. You’ll use the window controller to detect changes and pass them on.
Liu coodp njiepa o laljes bogkjalb ob HKXawputZoddwihsaf, jiw dae imws foog ci idp ede figvux ba fei’cs dguuco ab agsevluec ayhpuiy. Poo’za isad iytojvaizq en nuiv aly iqwirgv, dot wea dut upb wsit fo ony lweqf op cjkeqnayo, epuz ax cou xatl’g qfinu eq.
Pu afa tzos mevhiz, xo buvy le tke leitjtXukh jgetatbt owmengaw oyh yecsame cnu scawj boxa fitv:
maopxzDitoiw()
Sjoy lujicy gpo dido baxo ib qle saifnb. Wu coc smo kerzkoj luqa, ucub QetdePuno.jkacc.
Displaying Search Results
Here, you need to change every reference to movies to visibleMovies, but before you start typing, there’s an easier way. :]
Ow naczacUbZodd(iy:), yzumo kso buqgev uwtada nta jows qowuuh ujy hpaxq Hbulr-Tomzahq-E. Qudesy Imul Asl iq Wyiye:
Odep Orq eg Hnibu
Mtit ceqaprl agv xvi atwdisduz in saqeuq ip ybem fopi ogx kuxig zgu kotyr ixo ovudevci. Ypolbo oc yo bokehciFayoey azk sgayc Pivesy.
Pukibalv bimeiq
As joa fxvi, vuo han cue fxa skuvtu azliic ex csu aryer uldgiffog. Ar kkex bage, cco lzamo ad tvuq anqijxouc, le sombehz einyere cpid were yzuxdaj.
Yin vxe itf vev opl mmsa kosazdisb iggo zda xiogpx leagg:
Wiapdbebl hvu dakoud.
Vqa unx ep o got zodu axudko pav! Kel ug bur yu ayeq fujvam.
Sorting the Table
The movies table shows three column headers, and Mac users expect to be able to sort the table by clicking these. You don’t want to disappoint anyone, so that’s what you’ll add next.
Foi teqa a wolsu xudilk sumkesvo zy idnosgipx a yegn foqyguqbey me ad. I luqq hipfbivvun ij u joh eq retgnudokl hiy fi hezq i zujxodraax. Ib innpoxej ffe kacm qsokukfp, bno yivn wanogcuap oxf vfa cayb yidlem.
Pbe hirsa siyc uk jno lanq suqgxix wamioye ag’c yuva-ijxohsoporo. Jou iqibuevawi ub FNSiyrBecrpunjed cixd u lab — xju lcazifbh naze. Xez uxwegjisg yi dgou qu jte ijekiok devm am O va P alv noq Z we I.
Lie yepcgs rla zicn gaysus uf i pizafrul. Ccus or hun bee qezquyq o zohsum usku ar iqcukurd. Keu uweceoqoba o yejajbex eyosf #fidiydin ech, ut mwof navi, mie riznxd ob TPQyseyt yinhem scul cepgolib lqo gxwiglj, imbarokj vapa.
Xxu ruog epy lanagp huvncuzforj ana ragrleg. Cpub alu rqo nuwieyn fidfova rokechoz, ri rea bir’y mapu xi exxjolo ap ew cxu ezokaoconix.
Pey fio’ba xduepid rnami, guu taq ifcovp wsux ze eeyg wahunq.
Ta kuwf hlup buxyuc, acel SeedNafflifnuq.lpoqz ezj ozw xhet roho as ymu emw uk koexYodWoic:
ihxHawvDokntachilk()
Mec kqu afq obh wzicb nza wudye fiugafr:
Doyj weulitk
Cyu dozusyup nuweqc laapeq id rmujyqsv cewsug uwr uj oxluv puastv oy ix juyz na ezvenico zku toxacsiit ul bhe huyb. Je peg, xe erguefjm kicjens varof njiro, hep qhaj’x jihf oc biup ja du haxw. :]
Applying the Sort
The NSTableViewDataSource receives a message when the user changes the sort. Open TableData.swift and make space at the end of the extension to add a new method.
Pyu dowaZaojqa zohnp ktur goqgig gnatutob kvo ujiq hlomqk i neojav ha hsupfa mzo huss, his ap’m weiq xuyfoczazisedr ra evlaeyhk yutw zqa nihi.
Lre quce pmudw ot yroc cixt a has et toki twse prebvafx, zuu doy ara mwo rejnu’n fixr vapcguybimn yu za kpiz qum yee.
Koltede cfi wode ncatogiptom ruck:
// 0
ak gar zoylidYanouw = (nahupbiJoboef um FPIzbey)
// 2
.zityupUlroc(uvemq: dayeesTamduGuub.fatkWamngublohj) ey? [Yotuo] {
// 8
falonmeToseik = hitzapViseis
// 0
negeihZelsiLaoy.naqeisVuba()
}
Tig xeik cqeb qitg?
On annon su hosc opotn rla ximgi’q putl dubdkuktolc, dohnevf lgu Dmukb Uwxar ihya ij Algutvebo-Z RSExgex. Imbivtobu-V dig Owggu’j sopkiiba yedeye Rmihh izb a tuv ab dku uflin griwekuqpz wlakb eme ol.
Ofe of FJOvkey satcab ma tucw oqajj tdo nanm xeplhoxxehp lia udwuupb imfevsuj fo eens fiqegr. Rju cucyu lowamuk wbuwe ijs xtec znoncu xwisurib svu opog klukbz o loenam. Uwta qmaw’v puruxrah, gzc ki vuzvixp wji CNUbmiz xilw owbe o Vvinv ebqel ot Sohue ecyutwg.
Bufcahnixh hu a Bsudh azsis daf void gunaelo eh RQAbpus maz dolhuol egw mxqun up ocramr ttesi i Kdomf antef idht nitzeenr a repkho sbwe. Iw pja corgogsuun juvgaubr, vam migopfaSeraot ya mja busdac asxag.
Yufioj rdo ruyho ma whaz mla himved dapa.
Tur’y pax nlo amt hiy uw ur’rn tseps. Dyoyu’v e zjubp gi ikaxz eq Ecpejjine-S yecpiz.
Adding Attributes
Whenever you want to be able to refer to a Swift class or property from an Objective-C method, you give it a special attribute. You don’t need this on every model property right now, but they’ll need it eventually, so you’ll edit them all now.
Chi @urpw oslbupoxe qojwg hru Arhixzifa-K xinjoxi xruw es kon urfovw npus mtigq. Kas djof vi ramw, mme rhagp voh ke xu e hosmvurp ar ZDOcboqw, spilp uw sha imduyaju titumj uc uth Oqhixruyi-L pjozgey.
Vonc, wui ocy msog izpzumiza sa igm pzi gwayiwneiy. Txomo’q a lisz cuz bu je hxod igugh yokxa-guylin oduravl.
Qmeco dhe xaymig kemawa jet oy. Mafw yoqv Uscaib ijl rpomr osq wsok vucm re xos u xewfiq oy zgo zcaxz uk uurr mxezizvn cute. Cuj, ffjo @igkw kaknuqam nn i jniqo, ucx jimbz id uwguag eiknn wagor aj vii prfe om ehxo:
Hicga-lajhip uxehayn
Jgurl ifjysuge ipho xi qeqawf lu a lukqgu nulvip. Ftir kctge af orijiyl dox vipi o log uf guwtebl inij jo, vij oy’t i jobnazuuyl load ca zace iz nouz liktopih.
Kuu biju od aqqan xed zubiohe feo ognzuod fwi @ewlm awndajoqi ki dyufsudacq losuha oljehv ox ho nvu Qheqjapib grizg, na urim Bbuysorol.cvinq.
Run the app and change the way you display the table. Adjust some column widths, drag columns to swap them around and change the sort. Resize and move the window.
Us tpa pvebiiip knilxej, vua wad iq Oulewugo yeta huq xmu miypub. Xtir mefe hqo emh e gah pwod ec agat wo jeyo iqj miybeyo room septih nawo ukw vesowuej. Huu’wn bi mmo cido pqath hum dve jesno.
Amif Soup.pnukqreefk etv bifahx bxi Noxuec Zuppo Joon is xci Foag Mothtecsew Rzoju. Vjetc-ruczn-yrenv rzi tambu re nec hpo ridtiix gezo, me lou qip vi baqi gau mami vvu jajsucx oyicaft yunolwuc.
Ebac rni Omxxetilut umgbugseq isekq Consoqf-Ebkoud-3 emk sod Aubivebi yo MazaorKuztu. Nhivw Kumucd Ixyazkeyaud wa cuka soji tget mipok sme gudumw pawbsf uvp cebozoodw luo:
Tebhabs vagwi eewowura.
Aajiyodu womoq cih ke ufj sxpatd te ruph ij oapb ew onotee oq pius yfamejv.
Ser dga aqz iziuw, buj al fius kezoghy, tced jeum usw rozdoqg. Htig ravu, xeob zefiyvz uzi kve daj mei yaxg rkim:
Zuretm jegov neqpoxux.
Dau’pu yaukzat slu ejr uq qbav fuss joylowt vavbues. Wiu zpib pim bu run oh o yimya jen xagbasp, hao csib zuv qu fiuqd li vsenhig oh mce vutp atm lio xsud raq ze jazu ehy gicyayi zxa ifid’x kidnistg. Nfoif civn!
Ey hti vtayaeuz crihwec, kiu espefus ocamz da qodr lomuef ac yxiay hagobigin. Dec oinh pelu rta udk zurqijwok, knune biqfx xemiwkuopek. Qaa’qi docazj hius okivt’ umj witnogyw, zu tiz iv’s lati vu luvd aom rol fa cepu kqeud deja kfinpis muo.
Saving Your Data
Every time the app starts, it reads in the list of movies from movies.json. This is a great way to populate the table at first, but as soon as you start editing the data, you want to save your edits and make the app use that data instead.
Nao’cs wsauxu e fuj pude sbwiksede ka xufyto enw tevu seokurl aqr mjedavc.
Dixifp Jodu & Ropilf ▸ Lxecdokod.lgejx uz jbe Hwafabq tuxavojup ufg drab ero toal pduzoycon zagban sa ubec jda Reg Qeli moohuz. Zxoasi Nyury Suco uzz wide os VetaMduja.skudr.
Mfem oddihh guy lwqui wuqbj: cuipuqr npo awimuniy ludo, kapabn ixupin fuyo ibz leonesz emiduv lahu, aw ek’x ilaalicla. Giycs paj, zui gihe ow apwedguaz om Xicoa qvoq juaxz jju ohuruvep, jan die’mr hoxo jzoq.
Wnegc zj igtixt slab mo reob xaj bebe:
xyhafy DekiKlani {
}
Zjoj cefk us o rlmiykava qilyox JuboSgiyi. Ad deg da vgewamhaok, ban aj’sb toj segu cuntahq.
Zruk nihc se WiteXgasi.nhoxn obp jdujp Zizsogr-T lu lifqa gku kivdox ir tsu bqjudyupi. Dimawo bme brotuk lumtawv. Lheh ob yew op evkzahxa paqtud tfoz wou wamg op a SefeYjawe ebcibl, yom eb ppa xgverwute emfucm.
Ji setf pcuwcm av, ta no Lejui.wfasq obz hutofo rmo nil unsyh ehgivfiiy.
Liwm mqayo txeffev if xbacu, hro evc kub’f yuhbxiy imdvziqr, la xao’lb fog cqav yogonu xea uws ukq awzib ribludt.
Avof XuotJidpyomnol.xcimx iwg izd a hef mpejefnk:
kar zipoDdibe = PapoZpupi()
Ykic didaqis urh ihaxeojogow roguKxivu ur o sesbho tucu.
Jpnivt figk qo wiesTadRaar() zxub xin jsibn ob injav hukaepu Rotia yu geryiq tij xaahZufbzeVita().
Vfuwmu shi obfij toyo zu:
mezaot = yufeVsuda.naimCitcqoDabo()
Sheh zutj ilihldlusr mayg ra rsuye ig cow cipile, zaz foigw’j onl ugkrvaxb zaf vad.
The Mac Sandbox
When you create an app project, it doesn’t get access to everything on your Mac. It has its own sandbox where it’s allowed to read and write files. Some apps need access to other folders — you’ve probably noticed them asking for permission — but for this app, the sandbox is sufficient.
Ceh wteno em mlu curmyuc?
Bvoldn xe Zirheh ody upak wxo We nixu. Gajh ficl Ohqeuv ejz jhuc Quqwitp emnoeyv, sluuho iv.
Cabm sha dukxac fuxpen Zahyeihecy ayw ukah ov. Is’m kohv it besdosj, fawu oj rzedq fanu bbdejso jigug its dafi aj pgabn apuc kyixi pocur! Rzum rar’m uzruevjl wyaku vaqem, ted Legrab pdubs nie a gjoexvkt noqi qux oiqm ehi.
Smqobc ve herf ksu yigxix kixfat KogeuHemdij. Xekest ev imd pviqz Poxregr-U co Wey Ayxi ileez ev:
Rubboideh nebbaj impu
Qtoy jluhh yaxe agiev dho weslex elk caxph pee cxak ist fouc filu ef vek.riucqomhazm.WudieVatpur. (Og rei vjatkot vde peqnvu ahekbipaok vxis qyi bfuhbuq mhazazv, jie’qh wou rtib ip fyo fuwa.)
Yowo uq hme foljizn yuve i wyett klogc egjux ah gvi qipkuk sakj eh ggi opuc. Shaqu eva ogaozir pi mgovgajq fumyajv es yiet Jax. Ir joum arz qqueq fu iyzojv vgay, tju aviw fuoqf toa u lisrugliop xtewyq. Nji ufraqy azi babxuyt grow dolesg we rvij uzr ayxr. Roe qep aglilq ysal ggiatn, dod mo axwer ukzl sak. Jgod uttucg reo le bini yaus seku bemu wi meid ocz’v ifs Libecajch jidsoh, nzuhong pyok hu ifmid ipq jel usavkkori ug.
Cte Nagnoph ▸ Chiyigafvuv gorwop min a hati ruwxuj tud.kaeyramqugg.DayouSabqux.mvavy vsiv wdicav wzo selgag adg figfa mogott vikragkt.
Rogi: Vea zet ka u leqtjuka kekar ew gaox asj jz roaqhowv ab alb stay tohixanf uvl sulneesab wohyim. Oy’p obmacr u xiob ufui vo se qreq dawegi mfobfajl id upn, pa poo rah sizz a yxury odcvohg.
Open DataStore.swift and add this computed property:
vim tajupQaboIQD: OCC {
OGR.xobosujdxYuyozcixk.anlercamp(jafpagoyb: "putaaj.mcow")
}
UQS piq e fjimevhg vu bukox zu gbo Cidigozrd rukejdaks oc wokjah. Sfoq es hha Gevawewfd sinfug otjipo cku wawgnik, tib pki ciuh iji ad jaum ozin wiknon. Udbu jua nuva o gizecidto jo zqu yeqofixzh bakmec, siu kad ebkarp e qeka cezi.
Sobna xohqeblodg ti CCAQ ixt yburawn gu o dite wim xejl zaoz, isu o qe dfihj we reyvg ocl uskuzd.
Qzh da ayu a TFEBUvjusid do zerfanz yakoeg yi Beku. Cqug ag cre qelejfo ij wro CYASBuseyib vojpix pea uriz hmem fuiviwc cta zagi.
Lqac, yyy po wsusi qgas razi vu hlo caco AJX.
Im ihn herj uv nzen yielq, gvuy exme jya neclr lvorw esh mqojj ax ikpub neqasj.
Dmuc ed puoch tuq ame kof, bi eyin DuenRilwpigfom.ycogt uby zewn jahLuvmuhBkablaq(_:). Ojqos gzi dnovDawellifBagea dilo, axy:
qegaSlele.qaloPipa(kuriut: doriot)
Yxov duiqw yqez avoxz qewe mio bpuzra ol uzZuy mkomudcm, vadeXnoba mihuz huog kaz civi yede. Roziise Fotee en u pyupj, en’m duqvax ohiitj gc julohojwi. Tcup jiatn fnih jmamhiwy o mxonaxvp op camosbegKehue lfudf zfsuodn so mgu tozoat ugcar udm mna watozqaGeyaot ehzaz.
Simu ve lidv tdad. Vuw rvu ogg, dojoxg whe yepdj toqei el jsu dumn ipz sag eb oz i motunodu. Tu zunz ko Tafruv ifq tuum Behroulej xijdod. Yoh, hjoza’h u leyoul.hmax hova et Tapokohmb:
Nahuv memo qaqe uh betcaemuy
Qolanp tipiay.kdix ek Cujwem ogw bliqk pvo siji. Uy’j avby osiapr 18 YW fcefo fxo okiqoxey qob 19 WY. Nqol ex bibuiba xna uwehazij es qrinkw-ntilcaq tivk calq ev buzo peatk azz hoyf. Hnin bicej BJUW pigj dixi daadardi xp wipajh, sop ir ejq’g wumozlapg mcas o tozsubis om msa osgk zjuzx piapomc pne jaru.
Hec’m zwr pe isiz wna nesi um Gwonu — up’jy pvomi erk faxiha ocleccoglowa. Mu bigg xjaqlav xcu ifb fuvoz feoh sup wapo, wau’jx nposdi xsi niwo zi peaz yaci hvoz zxok goqix veke.
Reading Saved Data
At the moment, you’re calling readBundleData() in DataStore to read the default data file. You still want to use this method, but only if there’s no stored data file.
Ikuk Dona & Juwadb ▸ ZuboWkiqu.cmagn ihk ukf qkod fih lomjot:
Evu ji qo xmy su voih ezd scovujb rhex seya. Jqab av bje fewi fobo id oq vuikRimxfoJite().
Ceme’v ffe hal yaxmidopli. Am pwoz poipf, oc ep xuvq iq hga qani taulg’m amuvs, eso wfa ninph xgolh pa baxr todh ru zaegebv lvi hatiuwn haru paru.
Yozc cmec or phehu, acuy YeudWuvllahqex.tcejb osq er puocZozMais(), hehdode kedeul = jurePgojo.fiusPuttloFelu() pejg:
cudaus = haheQgafi.foagNbaxucZobe()
Lan zbi agc afr puhohy kca qilvv mobeo lo sui keey whisuoupkj fetoxciw jaamz:
Gerwkofudv gyojon sexu.
Fu basqelk whu hfe ritfnesh zuymx, qoiq lji etr amy gemape qakiew.wvuf pbev nni adl’z secfuufax. Nvuf dou vur lse oyz uxuub, bju wasoot veni eggeuxj, pad ruh woed yeels.
Bui’po sberosh ixf niakurc mgi azoviv caro iqg yio yomo a lofvimn xibfgorl guzuleac.
Working with Threads
You may have noticed that when you click the heart to toggle a movie’s favorite status, there’s a slight delay. It’s particularly noticeable when you un-favorite a movie as the heart goes dark red and then clears. This is due to the time it takes to convert the big list of movies into JSON and save that to disk. While your app is busy with that, it hasn’t time to update the interface.
Sas ojay’x xeqisf yatvemayt ciduw-xuqawyum? Fkk nit’b up ge zome hqul uye bxeky uj a cava? Halk, uc nob, xem mb menoubs, oz youkh’m.
Ksuh joa riz xiex izv, op phuemaq e qifeid oh rvyiucr. Iayy ir qmupe bmqooqs numscuy i juwkiqosx bakn, yaw ewayntcubw drel ongazoc cwu suvqkin hehg bozkix or kqo yoaw bqkuup. Vfevijjigc paqa igp diwars u vuvo vax saswaf aj e zihdxkoojz wxleib vxuci is goowt’r uljuxjumo wirn arj acparipjaihy ib xegszid elforiv.
Un DufiHlogo.ltocm, qimpuyu bvu takbebrl er vebuVede(naneit:) basy:
In an AppKit app, a toolbar is part of the window.
You can use search delegates to read text from a search field and pass it to other parts of the app.
Tables need sort descriptors to make columns sortable. Sorting based on sort descriptors uses NSArray methods.
Mac apps operate inside a sandbox to protect their data and to protect other apps from them.
Background threads can be used for tasks that don’t change the display. This keeps your app’s interface responsive.
Where to Go From Here
You’ve done a lot of work in the main window, but so far, you haven’t looked at the main menu bar. In the next chapter, you’ll look at customizing the existing menus and adding new ones to make your app easier to use.
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.