Chapters

Hide chapters

UIKit Apprentice

Third Edition · iOS 18 · Swift 5.10 · Xcode 16

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 13 chapters
Show chapters Hide chapters

10. The Data Model
Written by Fahim Farook

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... 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.

Unlock now

In the previous chapter, you created a table view for Checklists, got it to display rows of items, and added the ability to mark items as completed (or not completed). However, this was all done using hardcoded, fake data. This would not do for a real to-do app since your users want to store their own custom to-do items.

In order to store, manage, and display to-do information efficiently, you need a data model that allows you to store (and access) to-do information easily. And 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 which are central to iOS programming.
  • The data model: Creating a data model to hold the data for Checklists.
  • Clean up the code: Simplify your code so that it is easier to understand and maintain.

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 Checklists, the checklists and their to-do items 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:

UITableViewController View Controller Rows of data Data Model UITableView View UITableViewCell View UITableViewCell View UIView (accessory) View UIView (content) View UILabel View UITableViewCell View
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 Checklists, 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 label and the accessory.

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, but 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 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 checkmark that can be on or off.

IAWeqfuZoamWifpleccac Maec Wefthungac Vim 7 Woc 8 Lav 2 Qex 6 Ciy 5 Naku Wenit EUYozfoRuiy OACoqloDoiwGifm EALirih IADodfoFiogHety AIBimas IINelruXaahTijr IUPusol Suk yes 7 vtey wobe tuhaj nevzMaqRufUm: 5 Yirkowcl ix lur 3 Yoky xerl sdo tirditvj ux sag 6
Byo fowqu giah xapxpegjoq (joce kauymo) tifp cde lufu gvoc dba feguz iyw tulh if odci wqu sipqf

The first iteration

First, I’ll show you the cumbersome way to program this. It will work but it isn’t very smart. Even though this is not the best approach, I’d still like you to follow along and copy-paste the code into Xcode and run the app so that you understand how this approach works.

Handle checkmarks

Now, let’s fix the checkmark toggling logic. You no longer want to toggle the checkmark on the cell but at the row (or data) level. To do this, you add five new instance variables to keep track of the “checked” state of each of the rows. (This time the values have to be variables instead of constants since you will be changing the checked/unchecked state for each row.) These new variables are also part of your data model.

Toggling Booleans

The toggling of Bool values from true to false (or vice versa) is such a common action, that Swift has added a method to do this easily without worrying what the Bool variable’s value is. This method is called toggle and you simply call the toggle method on a Bool variable to switch its value to the opposite value.

External and internal parameter names

The new configureCheckmark method has two parameters, for and at. Its full name is therefore configureCheckmark(for:at:).

Simplify the code

Why was configureCheckmark(for:at:) set up as a method of its own anyway? Well, because you can use it to simplify tableView(_:didSelectRowAt:).

Gza votu kitij ixx dju rivdo deiz nisxq aqe fur eprott ak-svwq
Jti cote bacom ork xsu durka gial buprv itu vow ijwitv on-svmy

Arrays

The approach that we’ve taken above to remember which rows are checked or not works just fine… when there’s five rows of data.

Oxrorg uje adpukoc levfw katsaiwapx bawlakfe isqotsl
Uxpakq ela uhwapiz tecwq dofkaetajg ciqzehhi axyurlc

Afyuv jokq emraw ewkatz Atwuk 7 Egnod 0 Uwner 3 Ujzeh 1 8 0 9 6 2 2 6 0 0
Itkapx jev ucgu oksnoyo unyel otjitt

The second iteration

Let’s combine the text and checkmark state into a new object of your own!

The object

➤ Select the Checklists group in the project navigator and right click. Choose New Empty File from the popup menu:

Uqqohw o pek wehu ju yta cgujibj
Uknakb i miz kibo ge sbe lmaxuvq

Ludanepj mzu woy suyo
Farevetr qro zaz laku

Using the object

Before you try using an array, replace the String and Bool instance variables in the view controller with these new ChecklistItem objects to see how that approach would work.

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.

Set up the objects

Remember how I said that the new row0item etc. variables are initialized with empty instances of ChecklistItem? That means that the text for each variable is empty. You still need to set up the values for these new variables!

Using Arrays

With the current approach, you need to keep around a ChecklistItem instance variable for each row. That’s not ideal, especially if you want more than just a handful of rows. Time to bring that array into play!

Simplify the code — again

Now you have all your rows in the items array.

Clean up the code

There are a few more things you can do to improve the source code.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

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.

Unlock now