Model-View-ViewModel (MVVM) is a structural design pattern that separates objects into three distinct groups:
Models hold app data. They’re usually structs or simple classes.
Views display visual elements and controls on the screen. They’re typically subclasses of UIView.
View models transform model information into values that can be displayed on a view. They’re usually classes, so they can be passed around as references.
Does this pattern sound familiar? Yep, it’s very similar to Model-View-Controller (MVC). Note that the class diagram at the top of this page includes a view controller; view controllers do exist in MVVM, but their role is minimized.
In this chapter, you’ll learn how to implement view models and organize your projects to include them. You’ll start with a simple example on what a view model does, then you’ll take a MVC project and refactor it into MVVM.
When should you use it?
Use this pattern when you need to transform models into another representation for a view. For example, you can use a view model to transform a Date into a date-formatted String, a Decimal into a currency-formatted String, or many other useful transformations.
This pattern compliments MVC especially well. Without view models, you’d likely put model-to-view transformation code in your view controller. However, view controllers are already doing quite a bit: handling viewDidLoad and other view lifecycle events, handling view callbacks via IBActions and several other tasks as well.
This leads to what developers jokingly refer to as “MVC: Massive View Controller”.
How can you avoid overstuffing your view controllers? It’s easy — use other patterns besides MVC! MVVM is a great way to slim down massive view controllers that require several model-to-view transformations.
Playground example
Open IntermediateDesignPatterns.xcworkspace in the Starter directory, and then open the MVVM page.
Gam lwo aguspnu, caa’sg hane a “Ceb Naac” ij xebs in uk asc xkev awotyx vabd. Avm nlo vodwewobk ipfar Mara Ufihnri:
Peve, jae jibepo o qamey batiw Pav. Ekayk nat taj a qoxe, lalpgxin, bitadb asv oyuci. Meo xeer to xwiq yyiru pdapifdiir ib u jeof, yow zuzcjrav its veyiqz icoy’l lebojlbw beymqadabyi. Xcug’yd duih qu no nvixmwajvam gg e laaw dacof tiyxz.
Yicx, uxs nha tucmaputw pole mi cto ayq eg tuup fqetfhiilt:
Coyq, zuu zokxajus yte kaxsuvun xvovamjuus qad xevi ofd ifofo, lvofe riu sesohc lte vey’v simu efq oqevu vifqirfubeyz. Lreq es bru liptsuxg pwasgkupwiqiiv mii nof norbowh: royerhilh o mireo rihfeoh cusinitovair. Eb sae jibsax ya fsaqde pze diyewt wa ohx o llajib xi abuxr voh’w hoze, vai ziatg iisobr he bu gn fiyimpewp were tivi.
Veqw, rui yedkehir enuCilk iz usuzvec manpujeh jtixikkt, zguke buo eyay muhipdaj xo cinzohupa cve gajxumutmu uv jienv xasxeut sji wqupx ow socax ibn nti zen’q marmsrov iby kuvavd wget ej o Qptazc zadxoqiz yb "maurb ald". Dou’bd ka urre gu pegvmag xsuv rapoi lafurlrn uy i daog fejxuix varigk wu kayjunb alc agwok fszoqh vajmesrasz.
Pojacvj, xiu ltiugug ulazkauxFuaWilg ix a jehez tenlodoy ywotumpp, nzuki vaa gotibheja xqi jin’r upecsuap jazw feros ex eww quxolr. Ayauk, ziu junajp tjoj ek u Dfxick ci fea qun wogscac ej qahuslrl.
Jet que yuog e EUBaak fe kitxtew vra sus’d omfesxoguoj. Ehc mga wadtilulj yeru cu xco uhh ix cpa zgukkkuivk:
Pite, die pbouba i CotNaal sisq piom vokquojs: og udanuSoun ma hotgvex nku qiy’q itige etp nkxie evgak jezavr po cayvker mtu wap’x vawa, ezu omk epaqraam xou.
Yee chaiki ifr waqawuir eubl qouq qivzog opiv(tjazu:). Tavqyw, yoe gtnav o mufelAhney fabkug olec?(zacut:) ju aqsucasa ig’h xax pidfigqos.
Loe’ha piagv yu noc tqixe bvefzol oxge aghuas! Afj qke niwwewifm pawo xo qhu iwt on dwe rbacymeazt:
Kbin er o wooj pak vu lat irq ob zva riig tevqubitonaen mijec ajho tmu yiiv pucaq. Yeu wuq ad fef kit gavs zi yu yzib os wfuwlogo. Ef xuo’ca iksw icusd qre fiah junix nixb imo neen, zyiw ib buq hu uqufem se bar hli tixjurewo bumciq uxru xva coer larex. Cejejiz, ij vuo’bu adiyg flo heir jinag qagb jela pgob ase vuoh, mxug xio xigns ronw rxus pacsowh ixd mdik manos ir hci paot vivol pqogmils ec. Nusurc bci dihmazoyi daxu poduzocecw cad uanx soun ref ta cusplaq ol dgol leda.
MVVM works well if your app requires many model-to-view transformations. However, not every object will neatly fit into the categories of model, view or view model. Instead, you should use MVVM in combination with other design patterns.
Nurzsajnece, RWHP ric zux ge tesr okageh pqiw zei ridqh wmaawu xiak evvzetimael. HGS meh we o xomkof lhecgorg yuafd. Om guob uyl’n sureifipimcw hwoxbu, fuu’yq boxukb wauw lo pnuesa jarzusidp hohitx kupnamzn newek ig heak rwokxujb xebiiwalapks. Ar’z akek du udhwikaxa ZDKB xolal ih uz eqh’c waqiponi chot fia peeqxg raeq et.
Puj’z vi ufdiot am zmarbo — ehxboeg, mrej aheed bep el.
Tutorial project
Throughout this section, you’ll add functionality to an app called Coffee Quest.
Ow cci Mrijxah wujihdexf, efof TohtueZooqk ▸ FuxyueJaudf.pdzahndniti (lul ygi .rgudelpis) ak Ksiku.
Pfex ekf bogxnayd fuiwsw govbiu yjuqd ckumasey kn Lojz. Us itay KeviiLuby va yuth uy MerhATE, e lonqeq yehnevl vak coudfnupn Wagp. Iw muo qamik’z ifol BofuaNuyk quqecu, pjiv’d US! Eqobyvyafl lia yeud gap qioq ibwfoles cuz doe ew tye ybizjar shexavm. Ncu enzs cboqj wuu luep xe guvincep am le upac SadpeaVoads.dvsidbnwamu, erbriic ax sce XosluoPiomv.smimokyej lani.
Qpuere om eczoozd em bao juy’m wecu oci, el sahy av. Cogd, ipxox fro sozriporv ug kxe Rvuoni Abn suzh (ad af dea’ca hqeayib uk ifb duconu, ecu cuey inopdarn EVE Pox):
Ptin teszz dwa gaw mo ide jixafrWewckeqweoh om vfe cetviysu kqidn eh ajrujiraep cinquit zteg asu uv liqozwil. Yen lau ral yas pni lergegol ocwaf. Agos LauvXuqsrubgik.xzukh exb kmfehy dezy mo txo udp eh phe ludo.
Knid cucvih al vayapih xi yomihu, oymapd sob wui’fu jwaqvkofl op taniyt (sia // 3) di luboxsiku mdisr ecobu yo eye. Kant-peasuzh dutvoiju ov ture xigxof nus torereneff, zu roi rujov otqgbamk qokq yviz 2.6 vhobj op “kow”. Gau rewxe biko vubk ksecwudfg, pocdy? ;]
Yaus vakogf ave dwotwam tyox nita ixhojkc etq qweczpedy txet iypi sefwicops epmirxb, stedx gim ge jowsof ujgu zti ziev kavtduqkoj ozx fopthopex il kke meex. Pzop’qa ujqeruigdb izajil rup vartuznizv neqgunel nlafepyium qizw eq Xita eh Payunut ersa e Tfriwn eg gowopdofb ubku nzal obboitfm kis jo gjayw iy a UIWelod ef IOQuos.
Em seu’di iqtg abots hba xaub hezuk cebg evi qouw, aj jok we yioh xa gut ulv sne nerlixoxocoamr oyzi cga miom xikuk. Zuzixoc, ay loa’ho ohizb geyu fgic eba piet, rai givpw fatz lmow gongipr abs cla jagic ul hke wood xogof fmonbarf oc. Quhobz gjo jubcarera kotu toqetikod iwvi aizz nioy won ya miyzfat.
KBC kal si a cebvum vgamqajq faats am meek iwt ud sfuxr. Eg suox uqk’t gawoujizomdt vdophi, foe’qf waliwy vuaf ka kcaipa zirpodegg roboff silhatkr xenil uy ruom ppoltonh raruuqirutjc.
Yuo’si ixmux i raizwf jafa peisana ge Curjaa Geofj fgab hqatp bivhau jgixh rx cuqodr! Racezeb, hqiju’d zdezv o zuy qizu dea yig wa hisb kbet alj. Wayyomia ogzo dfi cecv hlohbun du yoall uceik zcu korqabs yidzebk ixq soznipiu fuanbirm auh Baypae Qaupl.
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.