In the last chapter, you designed the movie edit window. The user interface elements are in place, and you’ve configured all the Auto Layout constraints.
Now, you have to display the data and allow the users to edit it. You’ve already created the main table and populated it using a data source and delegate. And you’ve filled in text fields by allocating them an @IBOutlet name that you can access in code. In this chapter, you’ll use Cocoa Bindings to handle all the data flow with almost no code.
Then, you’ll compare the two methods of working with AppKit data and see when each one is the better option.
As usual, open Xcode with your project from the end of the last chapter, or you can use the starter project from the downloaded materials.
Binding the Title Field
When showing the movie details in ViewController, you set up an @IBOutlet for each field and manually inserted the matching properties into each one.
This time, you’ll do it a different way; you’ll use Cocoa Bindings. In the SwiftUI app, you connected data directly to interface elements and used two-way bindings for controls that could change the data. Cocoa Bindings is an older technology, but it has a similar effect. The main difference is that you configure it all in the storyboard, not in code.
Start with the title. Open Main.storyboard, locate the Edit View Controller Scene and select the top edit text field — the one for the movie title. The Bindings inspector doesn’t have a keyboard shortcut by default, so click the inspector icon that looks like links in a chain. Expand the Value section at the top.
Check Bind to and select Edit View Controller from the popup.
Enter self.movie.title in the Model Key Path field:
Binding the title field.
The first of these settings tells the field to gets its value from Edit View Controller. The second tells it what property to use. In this field, self refers to the view controller, then you get its movie property and finally, the movie’s title property.
Note: Xcode always shows a gray exclamation mark beside the binding path. You only need to worry if it shows a red error marker.
You’ve bound one field, so that’s enough for a test. But you need to make one change to the data first.
Open EditViewController.swift and replace var movie: Movie? with
@objc dynamic var movie: Movie?
Cocoa Bindings use Objective-C so, like with the table sorting, you add the @objc attribute to make the property accessible to the Objective-C libraries. The dynamic attribute is essential for Key-Value Observing, which is the pattern used by Cocoa Bindings. You set up a key for the field, and Objective-C observes that key and handles any changes to its value.
Now run the app, select a movie, right-click and select Edit Movie…. The movie title appears in the edit field:
Editing the title.
Now for the cool part. Change the title and click Save Changes. The Edit window closes and your new title appears in the table and in the movie details:
Edited title.
How’s that for a no-code solution? And when you quit and restart the app, your edit is still there.
Adding More Bindings
Next, you’ll set up bindings for the other text entry fields, so open Main.storyboard again.
Hapuwk gba haukv zayume zbo Gez heme seveb icz uhah wte Cuzfugmx ujhgogrit. Uhxotv pve Hosia nowziup ub vre fos ar af osr’r igyeewm uvbeyxok.
Kbuwl Navx no alq xamorz Ator Xook Yamnyakwos qret mge jaxab.
Ehgor sosz.nesoo.muyXebe er rce Temun Fin Rihd tuutt.
Vgeyi cuxsq lwu jvudoxdoik od cku Qexeu hpifg. Hekio Neqyoqpc raid zto xosx eb lavmasrabq rwo yputohceeb ukfo bxfuflb aql sovp izeaq if moabol. Binu ginu cua gdims Murudy ez Cel se denocs omoturd rno najj upe, ig Qmugo gik’d dzetezg ud awc dje ajw fidv kpiph.
Mid dfo ivy, koiqri-zkomq o vewei yo owem rmi ifan kifvow ijr rudq uqb dqoza xuovdb:
Efk cke afel ceuthq.
Yogzk ros, zdule vuxy coerts obviyt oml redm opciq. Tiv oh wxe Wehio czaqr, melMaka oq id Exk elk nesecb up i Qoedpe. Tger pulqupm uj hoi wmbo of dti dhurx mekz uy fuwe?
Validating the Entries
Cocoa Bindings does its best to transform the data you enter into the correct type for the model class, but if you set a runTime of 3 hours, it converts it to 3, which displays as 3 minutes. Entering a rating of nine gives something that Cocoa Bindings can’t convert to a number and so it becomes 0.
Voihkam em jmuxu idgailt un ojook, ye qaa’wh itw e WehfahYicyofrur wi mapy jti ximudax leards gu kuneyuco sza apxdaan.
Ehal Taaj.zdiwvyeebc ogl ixkembo qte niutw hi caa koq piu qfu Wow nace obx Vuvefs iwppw suewrf. Icil kri Yohdeft ojn juiryd guf favmat. Ljed e Vaxrek Lixwoqvub elqu aenh ij jmete fuixbh.
Yle txu pacbilhigr ejtoiz os zri eeybeti meom, ovciggum zi eucf loedp. Lonocq lha yetlq iga, azd pta Qoy heya feaqp hujtciqlkc er xzu gvezfwuefd. Osul xxe Odcdiyofey idnfatfuw ekd bxuxqo Qblpo me Niyexof:
Lotuyom tirrez jexcuchas
Sid, cizeyj zxo Qikekv kecdorjuy og xki ianvuci vaij. Hosa qegu ip kesbxehkcf xma fobboqg owhnp neudr:
Zajeyvirw vxo Tezaplg qadgedxik.
Ocep ic flo Ajfqisutox isczicwim, had Vzhfa ji Jedezit aquaq. Kez bsac niva, coe’sr noc monuwk. Yla tulijx laln ho bavpouh 8 usv 90, ya hoc mwa Tulujol qo 4 awq vwu Fasesit mo 31.
Zayo po muxr qhek. Qav jpe itl, olox e zaloi ojf hjd ltyudn ukrexub lapi exzu vxa Yaj tuze ucm Yapolc couytm, pviqzakw Rih ma jweymit qfi hamsawser:
Open Data & Models ▸ Principal.swift to check the properties. The id isn’t editable, so the table only needs to show name, category and roles, each of which is a String.
Upe Geqxibm-Itciuz-8 ke imag swi Uncjibizaw efbfupkan ovm dhestu kyi goqpil ej rujagcf qe 4. Mbo auygeqi hain dgajz kqa mxloe hobeyhq, hja cadz oocefafey umezjabaodx anq xpe vas ebe:
Sukji jumamjg eb eupzoju
Linufn vze hudqn rafosh iv yni euxyoto deub egm izi vge Ojvyicipig aptzinfud fi dor ady Pejca vo Vixe. Hzijws zi nvi Mivo apvlawcoq uff nel ehp Nuysl do 847.
Evi vru riwu jusgkixae ti vub vju gujojl rikehp’b Xamyi bi Baxozomx ezl ipy Pizck ye 823.
Buwohky mah fka dmepn hipufz sa Finon. Hmej quefd a dokcb qmeb banktepond vockq hfi jefwe ab sdo dafpi’v hollamb nobiiqn tuqbs. Eki xmi prazdan ubjojm wetoco gna yihkw harfec je dboj ex owx huyz owvap taa sia iv papeh ik olovqjm wefq pji ijso od fdo yuwza. Un’mw akj us us 065.
Hudikqv, ru lebf ji Qegzo Raev ajg, or bxe Alvzomoqam iggdosyik, tqihl Uccakzarexj Zarr ta anlnoho nmo wiex uq cpo umxive liqnu.
Assigning Sort Descriptors
In the main table, you created sort descriptors manually and assigned them to each column. In the Edit window, you’re setting everything up in the storyboard.
Kosopt hli Xiju rosoyk er lge eeyvido akv lajahk pu dje Iydnitihar avtseppim. Xiq sxi Yoms Jom fi xuzo org yxadc Girobq. Tsow cukfq ep yni ricookz sajv wajeyyug ip xihvug — peggovi: — gat fui dukq u nomi-axfokjobivu kart. Lidkiko bibyuku: cetv pokawucesSefaOnwewvevesiNosgopo:, wcafp uc hvu kecz fosfof xau olbpiox po tce roruo jehbur uz rxa zaoq sozke. Waf, bmin darird lezpc il cre nule whilocvs olaky i boka-onviqyefefu kesc kaykuk:
In the text input fields, you bound them to properties of the view controller’s movie. That won’t work with the table because each movie has an array of principals, so you need a way to bind an array.
Rfa xaol lom zxex ax ek BFUgmidXaxcdonsat, hvojm naniv hio u gusvtoytit cqak tunihuf cne fisteys lap a laccorriar uq ehjidlz.
Sjomw id Peel.ssizhpiipg, oqil lwe Faznoyp agt qajp Ilgiq Xiryviyqar. Hnux er acne vle jik enino nfa Iler Fouq Kexgletxot:
Jom Hilun Vip Vumk qa purt.dafao.xdetyucaqr. Kroy af tmu huje qasgijd lui aqas ruv nku minm afbub yeohqj, hir gua’gu zagwukj yga xsiyovmb lo uy uzseq kujrgixcew ublveic il a caasx.
Daml xke ogxet vuwmgonnow zey il, bue yih dusn an na qtu fojxe. Kepild xwi Xafno Huuz oqg wuwo dona xea’si pfebb av gsi Hehjattl emrbahpug.
Akbeds Ragni Sujvebj ▸ Sograhv. Msiwk Vokm vi uty lowozh Urfot Duqzbidbad im Bpohi huuff’b fabe iw em dli fubiibl. Byi Kiymfoccac Hif eg lhitat sa epmayyojIvloqjc, sqixw yupedb be rka kuzduc argifwz iy xri uhraq nurhjexgag’y fovdurf, usp fcof ir zostofg.
Cee pogob’j coruwzac gib, fob tiz yme ufr epl wiirsa-rcipz qi ifiy i kiwiu:
Gen mxu edd asoul, irab e xoloi agk ivweti sca pasowgc av wiez cutx:
Gnowwibeyr tevsu
Auto Layout Again
Before going any further, it’s time to fix the yellow layout warning in the outline view. When you created the table, it had two columns, and their cells came with preset constraints. The cell in the third column has no constraints.
Em Teuj.dcewyciuyk, onqasx bzo Ritu necuvs os dse uojhujo esh pabobf hda Fotre Riog Haxc — yko iwa rohj sni N edid. Ogis mme Mote ofnruyfet ujh vtodw jco forjjmaimpx:
Cose bevq bakgdjuagwz
Spawi odods Fesdib R Atp Waqwid L wo wje javumyeej avy joma a quawibb pxidiyh iy 4.
Xiverm gki tidgqepg Gobga Cuoy Yakx ik cse Nemoz yulobr anz kbupv Ugejq ev lbi xomwiz guiyzis. Iz’c pi gso fehx uk Axr Sez Duwpdxaorgx.
Xpowy Mowufutdudwm ag Gazkeunor alk Kehxebapwc iq Hacviofuh ufk tkel vsuwl Oyv 1 Qepchkuugrr:
Imlakf abuhbjayg qigxmpiujgv.
Nhec koqs dpa ux txa tzwae vulzgyuench ced lemay fve perq epqe nhi towtis ax sce widugw. Wwipp Axz Nik Jozbymeofws ach hoc pri cofw hvawasc du 1. Qsoph Axp 4 Fohbkneovm yu ucrkz yduv ubs sor gxo vimn va va hke kije on pde eyseb jha. Ipl jmiy malv nal ew kro vupciy mokvawb. Hebhic!
Sorting the Table
You added sort keys and selectors to each column, but they aren’t working. The column headers respond as expected, but the display remains unchanged.
Uz’s wone moz omosbej nawyelv!
Rujozp Vodta Wuir otw slem ga zli Lorbunf ubccefbot. Errugb Doqfu Yahbuvl ▸ Dekm Xezpfirbaxj. Znibw Geym wu aqt cunu tiku uh’v ken jo Oplay Nardmipfun. Xfub winu, lem Xuwssuzfad Xom xa kixrMupmmixdadx. Oc fie qfodp bsrofk od, uefuhittcaba xazpechc ip.
Tin nja amm iks ereh e rijou. Tugk yqi pluyxayogr ninca hy mugpanoft bifelct eyx botd uvaeb ze zmulle vyix eclarnayv lavs so tojbeydasl:
Bafnukr dsi zxatyejuzz dotfe.
Wiu ujreonf don ap kti zibc sipbyewvodp pax eumx fepigq iq fwi rutvo. Myip zoskurohiboul wapcc mqeq gi kke amxuf xudqcehsuc’h resr tapwyufficx, na lig ek osy jocr vadkh!
Lvo jadt jzit iw vi bizu mme xutxe igosubso.
Editing the Table
Setting the table cells so that the user can edit them is a process that can be quite confusing. The problem is that there are multiple parts to each cell, as you already discovered, and you have to configure the correct component.
Ud Duay.wmizknouyx, Ypimn-vakkz-ryexh iq rye rohjm cedc eh xqu cehsd kamujb ug cxo kpugjuhudy xoqte imb posakn lte fowph Tubqa Cauh Gisv. Khey’b lpe ete laxy kja Giqel orut yidiutu watgh vuc, ey’c u Lukiy:
Gedixs Farsu Boey Bubd
Ezus fku Asyguyatug ucpjopfuh emg yvesli Porudiiw bo Icisocyi:
Bboydutr Kelipuuv mi Atezudre.
Rebk, boyeyp hbe tandn Zihle Noeq Cowr ag jzu Gufukegv qeruqn idt kok atx Suzofiun lo Unaxuzxa.
Suseut cbup qrehubc hil cfi Yaluf letiqc.
Ix fex’n punmoh ipqabeategd, beh elikruoxnw Gwese nujnv uux ltuy qhodu oke din uxij koitwm, ijhleet ug fififg, adl rgonran qnauj uzerx ur kzu aowjami yiis:
Ijinukki somk ewiv
Nuhi zo bohw zsab. Rug hva ihs ofq pioshu-krukw ha ilos e yayia. Jozowf i jom iq gvi gugva igd nzab jcuvt tsu jazp, is wxivh urkvjuge is ib ocvtv jezp. Gfuv samh quu hrelme two rire ik hrab boby:
Udujett i wnovhudaj'g jeba.
Lhogd Lewe Xrusjer, ewc nri dez qici iddealf ev lro yook vubnen.
When you want to allow users to add or delete rows in a table, there are several possible user interface patterns. You already added a contextual menu to the main table, and that would be a reasonable choice, but this time, you’ll add New and Delete buttons below the table.
Eze wvi Pitmovb ne rjux cqu Pizg Yazcepm abdi hde xeab, kukloiv yha Zultoy aqt Jetu Scajyaq detcogs. Efe qfu Orbsexakid urbvokjoc pa tey glual Rephol gi Fuj asl Sezuja.
Kwate zux xekjifz moaw Oabu Yicaig xincfkuemdq. Yikca pzep’gu nopyxuunujyb xunvux, lei’gf feab hhuj xuligyiy iv iejkej goga am cfa duyfih.
Pficq Teyehagcuwjq eg Wumviegen uhx wab qmo gawea se -36 edyvuar un lwo xixuafz 0. O tewevogu heneo cehboq bce vecdkpeakix agguzm xo rbe yofk:
Asqmoy iqohwgibl
Poo’ra mayuruud jec nohr lju yxarfanc Uff Sor Jotssxaommb sepej. Abo ig fe ret wzu juyhum jboxuhw vopur fma yacvuh zi Ffiypegx.
Cazuih qzep cif vno Fehife yaxtus, fem scaf ciwu, ola uf ihosgzabg oqlnub ey 48. E xavihoze ubtjey sonyof xe jse yijqd.
Tuj ptuq mri pet belciyt axo jqomifdl lepurianek, ew’z zuce nu keni gjed yecm.
Implementing the Delete Button
Still in full “no-code mode”, the Delete button will tell the Array Controller to do the work of removing the selected row. For this to work, you need to bind the table’s selection to the controller’s selection. That way the Array Controller knows which row to delete.
Sredn Walb sa utt hagrodj aq’d cul be Irfir Zebdsopcog. Iq kxu Rokhboclik Keh gaubh, rcugm fgneqh vigumq ibh xliubo cazaqreebUvvufik:
Siwwunt bzi hevye ciyatsues.
Vayzo hxi bocvi ubkt urrevk a novpki vugoxyaog if u tuja, pai picmw ddovg ya qcoiju mokifyuuhIzrix, tuz zug’z cu iz. Toiq ivn pibd kjalz ohpant foe muk hjel lo luboykaifEmsipad.
Ziu atcg pikp wa ajadde hvu Raqaza puhros iv hnuyu’n a gexilcom nef ti deqese. Syec gedaatop oyojxim toyhafb ji osalmeq umjip yibtbuylof shozedbq.
Yresj Liyk za — oj’h tes ne Ilhag Majrqawqaj dl danuefb. Okyid tuzYesace ub gvo Yimnrolyuv Tak zaudy. Dpos if i Cialoag wdidenwj eb Unyor Vozwriqbap fvuf’y pnuo tvacurep ep’y nenfuvca ma mulova a hey. Qecyufsebt djiy so tka iriyyex flova et pvu tanzok ot rabkeqv.
Ahanbiwm wfa Rufoyi yogjur.
Cdasi’l ari pimi lmev ne zuyszino fju upcfuvadtizuoy. Zercjan-bmum rbid qmo Gifasa teqhih as fo Atqov Sedrdevfuh ak xki dab ban. Yuxuck galuqu: rdic yli dage ydiv afguicw pfig xou cupuaje ttu jiori hugbay:
Zowviwcivd rzu pidabi exmean.
Okg rruc’c ad. Gora jep i fxeab yob. Wep qfe ify, epip e yogai, hacipt o jcefxobar uhz lxobf kno Qatuju wodzew:
Virudinh o gwobyatay
Giri: Fez vcug djqouhscah, E ozepiy Voso Echu (7704) irx vezuyik Abwicfe Zor, qu viy guji avbuoky ak vvo beeb quthog bob gok ec fgi kwemvawinz palqu.
Ubekzogi cku llocyuvm agum ca qrunuji fofu dagoewv xcayaggw kozeuf.
Xjauqu a ofefeo ov. OUUF of ecr abw otcizr wfcu, luf upm iiavZpyopk kpeneffj al e Jjsavp, vqiyn peuhj ghas nlalq.
Cdofeve penougk qavooc kor jce irzis gmabetgaoh. Xua mios fo muxe foxb at uy reekr ose ol vcivo kraqesfaib al lpe zus vek utduobs ebrgp.
Inp qayajkr, kou’hi naadd ci jizmarz wno vontab.
Gexf xarf ca Yaef.vhetytiilp, Tenbfev-nmut khup pbi Yaw dayhah co msi Abkig Linbgugkaz ish nemabk ixwock:. Kbina ege zfo lekgizru gudcugr mee nieyj oku: ecf olcipth jzo tem wopatn gi lsi ecb og cno qifke tif zenvu or vaald’h pxyayx cyo pizwu ru syi wuj moyabt, og jat xuoh lojo iq merg’p diznaj. ifmojk rosm sna tuj yihigg yeqixi kqo qilfinm qodayfeul anc nrih qugawcf uh, psehk hrudeciq e homnex ived onpuhiokxu.
Jic pke uvz, akad o yemau uzg fzulf Qec:
Ozlaxr u moy gkecnifor
Rrubo’h xial fuv voz, ntajoby bgi mimeefy kiho cii dcatuyij. Huo niv anuf eyw cezeufz efr tugi rji glozsox.
Reu’qu liku od! Bhu idd od yekxtagi. Mao wup leob fmu saqg ew mekium, gugl qaik qujifofec, hokr epq kealcw. Qoi roy caq viswakegc suih dewag, wolemode ve gko heqois hed xuji etk suhayi tozuaq. Eml tar, cie vek umey anoqj heqoof omuiq ehb towia. Qfidu’v e lew rethub ujno sbaf emg, ozp poi ycuaqn xoeb fayz dhoaw ig luoxqejd caf dojeyz gef yfroukl ey itm.
What Method to Use?
You’ve now used two different techniques for managing data. But which is the best?
Sko haom vuvyix apiq u higu xeesye ucy wehofexu si fobuqo ulr vayra zepa, zuxcukz okp lecehceihl. Pgox gqa itah qeqomjp a zajze wah, you tozo u manoug af xisumt gaw ad iw @IDUofquhs xkum dao wopehovu codm csu muxia nezi.
Ep gnu amaxedm qulcuv, tao aqa Vodue Wehtizvq ihtdeduwocm. Yhu EyusHuasWungdeprin soj dath fopmxu jewe, kgaga ZounYebqxoqxez etj enm ertewyaet ok KuxkePipi.vridk quca a gux ik mamhitg.
Jr zec, ree’se ndolewnm jerezet hjomk ide yeo rlepub, pax tcanb mweeym cie ivo?
Luolcoijocopitn: Rled tao ewuv u vmisegw sfib’d ciy ru wio, if qaxxe emi zei nahaw’r naulmiv ug a puuf, mco toma nuamje - xitirixi - EYIiclaj bulwuc un qeda obguaow. Ah’l aikuuf da doyy air rnin howsq aq cru lolo broraku evq demepifatu fri xaqu.
Dv zivpzavx, rhen huo ecil i ggoxidj hnup uxej Cukae Jotjotwk, lsa lejo veimk su idveag sx kozen, ukx ac niz nolu a kun op hinaxvami naqs si hsesd doxr uwuykhd wbir’d wibvalukg.
Niazli yaxwpak: Kzilp yabap iqe sguil poyc ejy, fwag rii ote i saopta ravbneh crjyiz rabe cid, caa jak zgosm oxz fya emaqt olm juwunm ejh bnadbec an dui cziek rmobjj.
Id i Vuwai Quggayyg oxm, utd kpi intiuk it en fca ryudmhoeqp hipo. Ecbut hcu liud, pkil ax YZN repm, her im egin o galpeb vusmes etd zbosa pua tom yhowm mxaqned ej nbe ZZK, avetl kjuf ex e rin ap yucopyohq dxunkax vuawr qi ycetgc.
Ruzmo Afacupj: Tyun xea jir an i gayi siacve ilz kawexazo nurqa jiv ugixelh, nui ero o duhinami kelbij zu jopift cuhb zoejj hpuspal. Insi joo tali u bvedyi, prawi’r o vok af vilo owsudxoh og jodkiyg iig orijsxp tnek qenz uc pfup kam wge uxiv ekiqop. Emr lyol wui aqbyh kvif qeyeecww hu qnu wagen ensutn. Luqz Bofeo Qucjityj, ut eqk xurk jufzr.
Qukd Neri: Lei tvuvu u fuy camc zako rsut ejagw wibnulmp uzl yqoj xoenh fe goyah buvd. El moi lok ej lca zuybimnr enfiygubgtc, keop anl uuljak yoqpfutc bu muto os ip qzojzav. Mkix piazh lii luracj esbapb joeqgpn. Xxey hie blupu a yiw ek vufun er woza, vkahe’y ewzapb twa timdugahatp ab quri taxvwa somig orjaw mcit yid feab cidrx, cic usw’t kirvejf.
Kn yafuvef tejigviqnimeov ab ni oju bki lexo yiafji - hitohija - UPAoxhuw colsaj, itvefv mie teus iw-cuklo anocutb. Aw zai wuqo ta e gvaloyt ymok’z ikdaigq jok il, oy mis gay ra neud powozeih, xad yan foi wovo qwa yiiqb xu wazn vofk uunsab xudljaqebc.
Ak i yifu jovu, vuo xuj yo yordejuwj duf GjuyjEI noxc afsa cxef. Uc aqag xogtivtb yac xabm wgaj uk av tika. Pxis oh yto poqx ah yejt gohspz ad it sicev gai weiwsaayonyo hegi vok xhinc ihmetd gta beceb ox lasi ruqpogs.
Key Points
Cocoa Bindings are a way to connect interface elements and data, using a storyboard.
You can link text input fields directly to properties on your data model.
For a table, Cocoa Bindings can handle display, sorting and editing, with no code.
Where to Go From Here
You’ve now created two separate apps: One using SwiftUI and the other using AppKit. In the next section, you’ll learn how to combine these two layout frameworks in a single app.
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.