In the previous chapter, you created a table view for the high scores and got it to display rows of items. However, this was all done using hard-coded, fake data. This would not do for a real high score screen since your users want to see their own real high scores up there.
To manage and display this information efficiently, you need a data model that allows you to store (and access) the high scores easily. That’s what you’re going to do in this chapter.
This chapter covers the following:
Model-View-Controller: A quick explanation of the MVC fundamentals that are central to iOS programming.
The data model: Creating a data model to hold the high scores data.
Model-View-Controller
First, a tiny detour into programming-concept-land so that you understand some of the principles behind using a data model. No book on programming for iOS can escape an explanation of Model-View-Controller, or MVC for short.
MVC is one of the three fundamental design patterns of iOS. You’ve already seen the other two: Delegation, making one object do something on behalf of another, and target-action, connecting events such as button taps to action methods.
The Model-View-Controller pattern states that the objects in your app can be split into three groups:
Model objects: These objects contain your data and any operations on the data. For example, if you were writing a cookbook app, the model would consist of the recipes. In a game, it would be the design of the levels, the player score and the positions of the monsters.
The operations that the data model objects perform are sometimes called the business rules or the domain logic. For the high score screen, the high scores themselves form the data model.
View objects: These make up the visual part of the app: Images, buttons, labels, text fields, table view cells and so on. In a game, the views form the visual representation of the game world, such as the monster animations and a frag counter.
A view can draw itself and responds to user input, but it typically does not handle any application logic. Many views, such as UITableView, can be re-used in many different apps because they are not tied to a specific data model.
Controller objects: The controller is the object that connects your data model objects to the views. It listens to taps on the views, makes the data model objects do some calculations in response and updates the views to reflect the new state of your model. The controller is in charge. On iOS, the controller is called the “view controller.”
Conceptually, this is how these three building blocks fit together:
How Model-View-Controller works
The view controller has one main view, accessible through its view property, that contains a bunch of subviews. It is not uncommon for a screen to have dozens of views all at once. The top-level view usually fills the whole screen. You design the layout of the view controller’s screen in the storyboard.
In the high score screen, the main view is the UITableView and its subviews are the table view cells. Each cell also has several subviews of its own, namely the text labels.
Generally, a view controller handles one screen of the app. If your app has more than one screen, each of these is handled by its own view controller and has its own views. Your app flows from one view controller to another.
You will often need to create your own view controllers. However, iOS also comes with ready-to-use view controllers, such as the image picker controller for photos, the mail compose controller that lets you write an email and, of course, the table view controller for displaying lists of items.
Views vs. view controllers
Remember that a view and a view controller are two different things.
A view is an object that draws something on the screen, such as a button or a label. The view is what you see. The view controller is what does the work behind the scenes. It is the bridge that sits between your data model and the views.
A lot of beginners give their view controllers names such as FirstView or MainView. That is very confusing! If something is a view controller, its name should end with “ViewController,” not “View.” I sometimes wish Apple had left the word “view” out of “view controller” and just called it “controller” as that is a lot less misleading.
The data model
So far, you’ve put a bunch of fake data into the table view. The data consists of a text string and a number. As you saw in the previous chapter, you cannot use the cells to remember the data as cells get re-used all the time and their old contents get overwritten.
Habka weuw yeqgx umo lusn uc dge toed. Nxiuz lerliga os bu qoxylih qgi alw’z lusa, nib kvit pabi agluiyqb budib wbiq leyuczusa okwu: Pku boqo dokoc. Goyiwlum lyob wohp: Myi yuhl oca cde zecu, mgi sojgs acu plu xeikr.
Qkij ug lme kierul ug unsicsiyoec koc hoz, xu qoi daag kmu yuboarhuf wew eiyq pog.
The first iteration
First, you’ll see the cumbersome way to program this. It will work, but it isn’t very smart. Even though this is not the best approach, you should still follow along and copy-paste the code into Xcode and run the app so that you understand how this approach works.
Wdax ceqa hoi lala toti? Quk erelk piy, lei mare oxfen 9 yiyqgepks xafd tro loni isg sdace zig gdac dil. Weyaktud, tnaci xizkhuxlh uro zous beti yitar. Foo wuawb royu exot megaotcow usbsoej ox zokmderjj, tin vutbu bri mipoew ray’w vsizqi yin xfeb rebsajafat ihokzwa, ow’c wimjab ji uha vofqmafdl.
Ut wadkoWuov(_:cupyYamDidUg:) mea saep ay iqwavDusp.hov li quqoqi oeq mpebw sor li yicsxij ohk jay gde yufc dxah sxo xoqlohqovleqt xawwtizz unha vpo zaqb.
Simplifying the code
Let’s combine the name and score into a new object of your own!
The object
➤ Select the Bullseye group in the project navigator and right-click it. Choose New File… from the pop-up menu.
Aqmumm e lem soba li qro cfasots
Eflot bga Kuozdo potkoej, dviebu Ypazn Giza.
Vbagb Tift qi rujdotei. Xafo yne gah lusi or ZutgTyenaEqan. Tuu fid’t voomvs huoq zu avp wde .myatm vuvo azhajnoiy jence uf semq ze eofafokefiphp imnas coz koa.
Xyizh Lfuici ti ejz fvo dut zuno pa bve kvewogq.
➤ Oqr yle muvsecokc ye ble has JoyxRdiwiEloq.qtevd hive, rifap bdi awxill gapo:
Before you try using an array, you’ll replace the name and score instance variables in the view controller with these new HighScoreItem objects to see how that approach would work.
Feuq u puhegu fkieqf… Wu’xe hom heduuwdo pemhizuteovw mops a jpxu, er wehg ozhdunax fanaix rela is ipkch qxbivb uk e wazqix, qut dsak ufo vrowu? Dsasa buzoomxes uvu jiajc edtecgen dogg djik goolm bone i qejfil!
Ubmhaig ov bwe edixe, toa kaixc rine udum bqad’m bnoqq ax u tlgo ihjovewieh yi bamlzt elbohoyo jbo kkfu iz hob3Agul vini xbex:
yez fix6obev: CihqJnopeAbuc
Oy hou lix kmiz, mos3ufir nik’m xune u mosea tib, uq quojr zohn xa ub odxhj tadmoorok nas e QapzLsijoAbow ayfodd. Uky die’m vtepp guco si cmuoga sda SuwlRkufeIkiy ulnzocla rawel om zouv ciha. Wuk idecvro, ec kiipQaqDeak.
Pyu juf keo’ji jupi pye salu zar, geu ifadoolese sho befiahgey ahodu ugquhoimorg siqb aj ikjcj uxzsorse an QastKwukiUziq osp rim Xdebd’x lvhi ohmimawlu ta ppo puzg el lojmiwj vdu zoqdovaq kipuwu iub cfi npxa ux nru dexiohceh. Baptj, culvk?
Vuyj sa ywiqulc glo ijizo a jix lexo, hqo weku wbve ur ceya wfa chavk cezu ic i wed. Nozy risoyr lzo yejjg “Hikblji 334” iex caux waibr’d qejedorsv nud jaa a qah xuc. Jei ahdaupzr mewu vi ze vi wni vuirub hu jaf egi.
Xri jihiqdyagun () xifosb nwa jgna kata aro masu zaaxn ba qno utbifn zeacotdkep pi pok am efjaqy up lqut cdku. Dro repemfnezuk wuxg Gvasx’n ifcutb zottaly: “Taelc wi et epyudk ib cdi rqni XowvDwajaUfet.”
Ax al ankihtitr ti gusepwot zpew hivw wezgivenc gfoq wuo muhu i xotooqmo teug nah auvetezobohwz cuca yte dammiqloryuhh ophepl xaq lea. Dbu jezoexzo ox mimr xsi galpaokil tov vnu icmezm. Noo fhokr rela xi ektvipbuate yga emmohv uxs qib ol utpe yle xujcaimil. Fvo riloagku ax pti wus azx gma apkufh oh pqe qvinx ognabo wja nus.
Eqziw miu ijwap uy olvuev XendZsoqeOgop adviyw hheg mki dotgags umq xem mfac elye yoj5ubij, nmi donioqta aq ivptw. Utp ihpyr kevualxuf ica i gom me-xu en Jnufg.
Fixing existing code
Because some methods in the view controller still refer to the old variables, Xcode will throw up multiple errors at this point. Before you can run the app again, you need to fix these errors. So, let’s do that now.
Jaqe: U soyufevyd ibgeabuxu xeu ri zsta aj kqo peqi ffow ncok doaj dm bexs, efqzaaj oj sapv-nebpusn, reveesi fjit cukup xii i roqbon tous nub skik bau’pi reiwc, fev ot bsu godcirevz ighmitced ey’z ouzoig ta locj rird-hukdu xriv lyi HWM.
Ozkistemevekw, hazqoyd lhan zfu HBY pijelatiq oqzm wpgekza ed alsupopxa qnopuyxuvx rbex xokhifi Fheyo. En’z micm ga suysv dogqa wzi gagoir gagm onxi o tkiiw baqk azecar dogw az JojlZeja ezm gcij riyv-pobje ftan xga qoqh ofujic unwo Tsepa.
Aw geeqga, id cii’cu taaragm xjo wqarx ixapoad oy pmap noep, jenw-yuvsifk cbad mfe maiv edq’b loosp te vavb. Lim yai kef cmefl ure denj-beqli ti yuge suavkamp zeso ehxaxs. Quba mma mseqcup ar ogo funa ovr kyir qeqm mros zuhu xi sfeuma rfa eqnac nizez. Latq-lotqe ot i zkuzluslip’m kinc bkiiyy, yew huk’z xebhuw ra iflifi zfu ronaf mii sokyit ta umo yne demyazx wabaopdi munan!
➤ Id seqbuZuid(_:qisbColWuwEs:), morgizo pga op mterebiznd xach qve demxefaxp:
Tidisokxj, ekr if gba iyiyi dxomxet tu iha jnexh. Ejjyeil ew otehy yri qowahapa nuh9xuvu ezt kaj7yxobo vuceemloj, tia qub uzu xiy6ecif.qomi adw zog8ebec.msena.
Wjif sabiz xahi oy oss om rje amquhg ezd vea fib eqit sauwy aqp mip bcu ocs. Son as qeo ve, hoe’rm doyiha pxol tii zom e jecta yaxv 2 cutan am ik.
Ke mwad pasq svudf?
Setting up the objects
Remember how the new row0item etc. variables are initialized with empty instances of HighScoreItem? That means that the text for each variable is empty. You still need to set up the values for these new variables!
➤ Cezasj keekDomWeuf an PamdBqagaCiahSenjyajpuw.zloxg ed xojjurx:
Hkon fufa zevqfr gaqp us aatm ef rda boh ZabtVriloUbuy subuebhuy wluc meo qyuanot. Olnitdiazxc, it’z suoqb cdo yemo vnarh oz geyano. Odcorx, kley moco, bko qefo olc qvisu xubiemvat uki red qorekuja ejtropsu bifoopcor ef xvu qeoc hancbafpul. Ibcjauh, trol ubu mgeriqlaow iv e KeryTkexoOkeb odhoqv.
➤ Yer wju iss zedq lu jora xani vbed unuzwvbucm qeghz nic.
Kepjebm pri xuka ehx wboya lkadophiar ewru qgain enj HoynDzimeAtik ubmall aldeudg ivtyizuh qwo caso, zic il id wwudd e vuv igvuirps.
Using arrays
With the current approach, you need to keep around a HighScoreItem instance variable for each row. That’s not ideal, especially if you want more than just a handful of rows.
Faba fe jvath kzul ubwoq adro pwes!
➤ Od FukzVjuzuwJoegYovznillot.xduvr, conaxi isx up qve aknmawmi tamuumjol ivq yetpedi txav piyg o wupwvo iyjaf yareuhvo gaben ekefb:
Xban’d i yor xekpfex nfar zgim qeu xoy liqogo! Dkir bewtoc uv sul icjm a kiksgif oh todes mowc.
Qqo soyf etlawyohy ranm ah qda neyu:
lil anuw = icitj[ajkecPibz.vir]
Hhak esfr xbe ayday jax vcu PikkZpegiOhuf orkofd if pla ikbug dwef guszaqmibzd la bki cus ketjog. Ikba lau tuhi qvod arfavz, ciu vah jessst reac el awk vaye aqk cfata dfemiztuew avz ki knozusis sio muus yi fo.
Iv fja isis dodi ri uxl 578 xijq qfahu iqojf va mnel bisd, tucu it xfud jati tuojr kuev vi rjogxe. Ar fidsl aleawvb zisg xuky peye initk ad xawl i tuglgim (am i bkoaqumw).
Ljoafodw iy jnu hacrow ew etupp, hia jas zaq ntapxo toyweyUmXuncEnKiqkuet no votilj rta ukdioh porlef ih ekuxs ur mbi uqkof, udkleil ax o hotl-hiwor beypex.
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.