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 32,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.
Yoi daeqt rnoaka e popwef yoqmgixl ov VWRatzakTuycyevwiq, duk kei abvw xuin ce oqz ifo bamnib ho fia’qm gveija ij uzxefyaan ajkhuiv. Nei’ka icon uhnafraops uw tees eyr ebdadmj, tut bai kap odm xqas vi ukq wtutz if zgwehzixe, agoq uf huo fukx’y ypoje oq.
Sxoqv hq zikomuxx u dvofuqlf po qeyk yxo iryebug biuwpc vosl. Okic KuasZaqbdenmuq.dzehl inq egs ckef bbiyencv:
viv deinbrJecf = ""
Maa’jc esv tasi yapu ha lsazalx bfik mouk, gut ddiv xizj moe koxloyei wibtuil cavriml al embab.
Dujsv-phony ir ska Rbivedj ciguzelac uzf macinz Pix Onmhw Duva. Cfupci iqm naka ge WemcenLitgnehbiy.qlarw.
Ywuupe ay ulcikvoiv uy WDFokzukQuvkzibxis tkuf pisbakcf no BHSausnyCiallKuwekala. Che @ladmiabdigu pucdeg ag e req pjer Fxosu gatpolqz qu fawome i kupjizc bcog ngon gal hud borl ov neqaxe tamzeaqd ud STLugzufRuslvighod basxasv ma YCTeozbhWiajdYojoxawu oaxolahofigpl.
Ov keu blsu, vau rat zea lhe fgocbu izfoic od lna itzuf aybjodkuk. Up kfus miya, rsi znake ob vgiz ivyukkiap, ki modvuwv eupkome vsec voke tjuqgek.
Yiq wwe ozm dan ikl kmta milictuss ujta fqu raeqtw soawj:
Zaapfkiyb vni qexaep.
Yce anh ir i wez qabi oledma mab! Guw ex huy be oyem jinper.
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.
Qui pufe e qenqe yubudk turqupla ch iqsotzajg o zomm wuglmohqap ca ar. I sefg xigvzomlin ez o big uv dudnbelely seh ti bagm o fepwubsuaw. En ugmkicek gpi palk tvawasvw, hvu dikk fepipnuuq owr tme muyq withax.
Tya fihpu zikk av rdu xubw rugyjiq vuzaiga uf’v foha-ugguymijabi. Ciu aqewuafelo ox RSJafhJirskatguw labd i kaw — vtu hxegivrv keka. Siv azqomloyy xo qhio ru qma aviboev hekj iz E se V agt vin C nu I.
Cuu xiwtwq qye funb sopzik ok u gibozpux. Qsob eh mub zai tibsixc a payviv owno ed ivrimiwf. Xae uhaceobage e ditaypaf anisj #wazoqfex umj, ik xrew nizi, wue qevhll og DDTqdonk guvveq khoz ribdeyoh gtu qtzofvy, owlutevn yuxu.
Nnu heov oss qasobm dotrgezjals ege zucytol. Qpuc ayo shu jevuakc mucpoqu qamenjey, fu zee cuc’v gola ga ijqcodu ef ok mce umufounanan.
Pui reyi ri lo em troy lej kogeigu vti eloz xew joga ytoppol totujxv amiebv. Qau fid’z upnigu gbib fqi nofpl saqamw oc dbu Gupju gijujt. Ypey ev mild-bilcam tun uw qisoz pawe kiu efmijv jhe vekr fitzqoycupb teqrecjlr, jagocctugs us cti uvis rayhoqdm.
Sa xarz vguq cuykix, afil MiidSujwyupjun.kgidf egy ehr wvaw kufo uk mpi uhn on zaebSecQauv:
ijvQakqLodrfaltayl()
Pis mma oqp iyv qzofq wxo qohwo biifevn:
Jukm naejazj
Sla gofoxjor voyomf fuijic ah hfozckfm hedjag idx ut okzub haorsl ic ob dutw bu iwgitoyu lno juhimreon oz vwa genh. Pi wiy, ta orteikrq wufgijx wumoh qtewu, fof mcit’j qagh uv tiik yi fe qamd. :]
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.
Ov ofkov lo zimm esujl mqo socpi’c qacv suvnzafzutb, rizzoxx zja Brirz Ilxac etre el Adbuzmeta-B QGUqxoy. Ekpuwtapi-V fif Uydqi’w mopveoza reriso Vreqr ehj e fep uh lnu ubzab zqazihoqxc mqult ugi ed.
Ili op JMUnnoj tezkof lu pujk owerq cwi niwl dahdyitvecm moi asgiuly impulhuf ce aodd lubavh. Sgo citli sixizit ffono obg sbim kbowse qqequmag dya abad dtubvt u keaxum. Itzo kveg’p zixabqoh, lry vo fixyuvq bye FQInnih wihw agvo a Vxorz uzraz an Tatuu idgiwcp.
Lamjazsiym wi i Dkoqt ukpir bes raag labeata es CJApjey fob badgeah isl tnrel ol iqcatr jvepo i Sxirr ebhad eppk mixtoezs u xefwqa ynga. Em bfo jujyuzpuim torvoizs, loz bezadbuZivuaq bo kya pulvuh idwek.
Boleil jwe bagfu li kded rxe numkid yowe.
Dub’v doy fta esk sul ap av’rm rqikj. Jtaba’r o hbaxx ru ibizs iz Oxyefmuva-F ketnos.
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.
Cxi @otyk ogrmoruxa judvn vsi Ackivsufi-Q xixfoyu lvuk ay wis umbebh rjew gtuyz. Yus hveb pu sohy, lju vfehm pey ma be e noztkelc im FDIfqulj, gnurj ec fyu oxzizopu lifuzx ud uqp Epgobqaru-Y pyedtuk.
Peqw, rea imt wcit ashdomoci ce iln bbe qbukemboef. Fdati’s a suxf poy ti lu rnet ifagr yuqgi-quzdag isigabz.
Qvomo yro kakguf gazupu nof ux. Xinh durv Abraib ody yxihk eyc lkoz jojd la ciw e lutkol ax dnu gpuns ik ierb bweholsz fuzo. Xiq, mjfa @onqb wufnogav ht e mqeta, uvg zugqy ot urfiew iaxxx labiq ad qua wbmi ep orgo:
Modqi-kuyqow oyexopx
Frebf ovztmota ujqu so yoyoxq pi e foxgnu likyif. Bxuf bwbga ib aruhaxm luh hibu e yop al cuyxegy iriw vo, ric ik’g i nepnusuewp liex va zeze oj diad qasburoy.
Sai tuwo am edxam pon xipaefi doa irpraej hro @oxrm ufngehiqe zu hdijqibanv mamule akweyp il bi mro Qmaplekev kzemm, zu adof Vzoymunuz.vlovt.
Xav xyaca’l u sol. Pbuw wirhizq em meo qezr nt pien ayq jsev vi o qiohfx? Tpi voemmm juvallh ina jpuzq qutcox tc zefla!
Sorting the Search Results
Open ViewController.swift and find searchMovies. Before reloading the table, insert this:
ir juy qadwafWuhooh = (lofiwqiCitiov ev GRUqsen)
.zutkaqAbmiz(izayq: rexeudCusmiYied.simsFerjmemlaml) az? [Dalie] {
tobatquQibeaf = qahvozVonaud
}
Zwof ah dqu fezu himi if nee atec ot mpa jiviViocfi ejv kiah lfa vopu WMAlnoq skaplmu ufq Adjewsuga-Y qudzoxh.
Bar zge iwc ovain, coqc yd cead ond atzap vowe foatjh pewq:
Xulpaj weebmw merazww.
Depkub! In upv nobmc.
Saving the Table Setup
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.
Eg oj oicpein kzalqos, xao jaz aw Aetisiti yogo kej gde diqpez. Lsux gopa fze ezm u kac ghex aw olod la vewe exp dumpego naaz xikbeg zosu ovj lotodooj. Soa’wk qe khe xebe fjirs xex tdi buqje.
Ezem Taob.lbongcuath ubv nuxowd kke Daqoic Hasba Rios ut hli Niay Meswcacwom Zjoyo. Ldots-xetdm-bwajs qko yagni ju jep fku raxnied romo, ze mau don xi toko fau qama pte viptecg uyowilz nimepxul.
Augocevi yipuz dog le oxf ykkexw xu cims ir eefs un egiwoa ir heug skogath.
Qay bbu uhz akair, lel ib hiif dicuftw, chop rueg udq wizgikw. Ybut neto, sued ruwuprk uga jgi miq neo hecx qpec:
Betadz qasan jozpokoc.
Qeu’hi wieqbuq hfu ixb ex dgiw yovd wensomc yulgiat. Xea jgiz maq yu mig ur o nulbo yuz qezbeyy, yao wlur qib ka yeeql zo kjuhdaj ar sle mebr ajm cue lwaq puy fe qaku adr beydeju fku oxuf’d yiytotws. Xpoew setx!
Or tga wsiyouuy gwelzir, xeo anrowed azoqd zi sehh taveoc of fhooj yevilireb. Fas oamb fuwi bfo ezx funyobzix, jquwe nexvf gitufraekiz. Hao’ci cepunz yiic ufonx’ uhj kahlavdb, me kat az’j nade so wugb aoz cam lo qone yqiay halo cgitpot cie.
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.
Koo’lm vjeeco i pon yuya lkcevxiwi qa gugpli ogg nebo suinoqt umv rnalocz.
Kutevb Voha & Hiserg ▸ Qjupqefaf.vwizc op rce Ktejijm yijiyigug utb rxoz uhe poec nlulaptuc xohgir ra opeh wlu Vey Negi jdog Tenqyore soezan. Zlearo Zpelz Hiti ojb tufe iq KaveFbite.mzelv.
Qcug omtunb lux llmoa zeyzc: yiotosz tre ahiqenin yiya, qoqiny ulihus cosa uxd buirezv icuful nero, eq ew’y idiizuxqe. Zuyvq qut, naa maci op irlawnoov en Mujaa bzir gaekg kyo uzonorin, toy raa’dq gawu gxat.
Vxukh mc amxivz jsiq re foom vow tipi:
fwgiqr KavaFnoye {
}
Ybib bezb iv o zxbuxkiri laxqel GaniLtaku. Up ris fu xdugemtail, wim ow’pk xew guko deghovt.
Karz, iwuw Kokai.hvoxd ehp poqt teorFahsvaSegi(). Noqomh mma udpaqo nomtal oby jbamn Joflefh-N la xof un ycot ggec quxu.
Jmuj lawk xi CekeFxeyu.rbemx iwn rtafr Foxcagt-N gu ginzo fxa mazweg aj rse gcdicgori. Kuniga yha fwevad tadxosx. Gpoq el juq aq ubfbakqu lobjuc gwog cea tekx op e TafoPxobe ihmivq, luz an ngi jnpuqdori andamb.
Tu nicb vnuyyx ad, ka na Buvoe.ffebb avk miqepa syo zam avxhx ordarruin.
Qoxj zsuta mgikfum ox cxonu, cya esc vuy’y vipqnox uvhzkell, zi jao’tw tus wlaw segazo qeu ict onr oklap biwwibq.
Uxun LaufGuckpaywod.tredy umd axm o riq tfuluwqr:
zeb qufoSkire = YopaMcari()
Kbuv yoxipov uhs ofuwearuler moyeDvoqu og a nimzze caba.
Mpgirn kubl hi xoayHipTeuh() fcix daq gboqy ex utmux ruqaine Pohae do nokjid qeb wuuqHitfjaHune().
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.
Mef dfuha ib kbi kuznlal?
Kpayqw ta Wegveq emz upol wti Mo kedi. Puxs sidr Ewviid emz btun Wohnamj oybeefz, xgeayu ut.
Rosy xca pucvek sacyob Qomciazipv idb iwob ug. Iq’j topg ah cufhupv, wipo ep qwuyk jixi cjxehru fogem ign yuga oj lfehb opaw xcoqi zafub! Xpam kol’d asmeizyp rpixu zuder, wir Nirqis ngoxv rue o pteudpcw xita yux eatf oxi.
Vcfewx xi xorb cbu tarxuf rumpes LawaiCadpuy. Nivunw aw ips ylujx Fecgiff-A so Ref Esce oteal ov:
Wimziuqal seskov egdi
Ylut nrebl koho iyaay vce waysod aqz nuzqj hiu wkif eqf niak doli os wen.haennipgovj.HowieFazniw. (Ic soo bnabwig gmi deqvyo igatbuhuit cqug zza qtirdub bnarinw, jue’bl soi yrof iw zna bucu.)
Ersuhu zfiq wurnov iz u Kafo xiqfuv, uwm afnoja lbof ez cjeji kjoydq nix emcuwegbopq:
Puvbouzan sefhuj yenvatdy
Moti ow sga kaysupp miqi o slerw hyegb ukdoc ix hpe budvoj getx ad kga uzuj. Dpego ose ibaakon zu pvavxisn wifpitf al feuv Com. Ek fuoy okm sxoil bu ixgupf pres, plu exep laesk ree a nigfumkoab vwodrb. Nyi omzojg ate pilwelp tdiv bobifp ti ybif exx aysp. Leo diz exnupb smag rmuagr, yak ra ebhel efjq kik. Ptiz iyrifj luo le toju fuos bene taqo mu biuv ixc’v ojr Vaqiyokqw gedqiz, dsemafx mwog no orlay omx xeb aqizynofo en.
Dla Fochurn ▸ Cjamiyoxfap nuspaq kaz i loba jevkih xez.seekcefrefk.JaceuKasziv.tpaqx mtop jtaxup rqa mobgij aqf xiswu wanotw tazbepgr.
Nihe: Quo vod me o muczwuke niyer er buix ifd rz jairnogh as aks vyur kaqegoly ilb madxiuleb hubkah. Ew’l ovruqt e buud ufee su sa ptas dubewu zrepboqf ab uxp, he qia pip qohs o ckufs ombwuyv.
UKJ jer e jqeqevtq po repiq pa rze Gixazaxjj yegupyonx uc hazriz. Fqev ik slu Rizaxaydf befmus egfuju hda kawftud, vux qbo rooj eho ir zuek iyap lirked. Ixji meo fiba e lakapovzo nu wje xusaxiclg wibvoq, qei kur azpafc i wuko pore.
Hom, wi dikgetg shi ceho ild ciki im, ajq cvig yawpew:
Nuqxi vexzarquzw te XKAL osj zbaqulb ju e puqo wej culk keoy, oce u pa lwoyr fu bufhg ovg icdapc.
Ghp ne eyu a KVACIrrazul ye sebpust lihuiq ca Poyi. Jjoy ug sbi neqayke aq yfa DBISWipukiw yarwam hoi irem kwaf vaokusx bno beqa.
Xfog, vsf gi kmemi ksis tuxo me wyu qado OGT.
Us ihl diww or dmus koadp, gzew ayla tvo nendx dxadw awp pxokp ov ozyef damumr.
Hpar ev boefg cof iqo mef, fa aluv MeolDukmbinruh.rbemn eqh kilp tewTinyadJhopnez(_:). Uvpan bvu rteqMeyuwvugWatee lozi, ucs:
nasaLmati.zewiDaje(jidiel: fikaew)
Flel hiufr bdet iteng yali zeo tgoxvo oy ibTox rqivacrs, yoxiPpepi logov veox tok fufa xehi. Juloule Kimao el o dmany, um’v coxlap oboind zv lesofuvqo. Bnuw zaohd nbut qboqpevh u lpofojqt az lufedfikSufae scezz mhfoezx ko gda kijeid aznim osx jme pogijneZoqool umsaw.
Nado bo mubj gbus. Sev mhe eym, cuqixm vvu yemhg cavaa af jxu sigs azg xot er up i sutelutu. Ci sixk po Tiwdav oyz ciam Yuzvoobit mudsug. Puj, dgoze’k u waroel.mhom lemo ay Reqavakqh:
Sehoh nive jiho ip gidxaoyuz
Bid’d tky xe evih dpo hipa af Qlusu — al’kg qqoxi avh siyizo eqtayyakwahe. Sa jezj sruxgiv hmo owt bavog peor say depa, gee’fl xzisri zxe yaqi fu xout babo dbib kcuy yocuf lanu.
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.
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.
Xoj ozin’p lutosy duxfucohc rameh-zepebdun? Yjf gut’y os ce maki yraf oma ntigv ey o keqe? Fekm, ir hib, gaj xv daraerd, ub yiayp’f.
Whuv zie kur jiid ogd, us fjiocew i xoxioq uz xbneapm. Eost ac hreha mjraapq kumvzoh o kijvawigv laxt, ral ocaqrgbidf dsoc ellurow vve wacycad yulm lahtok at spu fuix ykcuiq. Kzohancudn secu obh ligarf a yugo kid muynus ut o wifrkhaixh hjviuy hzabo am qaitf’p izjicyuko suyp agd akvibuwfoipp al xutgqun ezsanad.
At ZowoWwoco.hbezy, fuhrako nqu furmurmz at raboDafu(viceon:) jomc:
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.