Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Getting Started with SwiftUI

Section 1: 8 chapters
Show chapters Hide chapters

My Locations

Section 4: 11 chapters
Show chapters Hide chapters

Store Search

Section 5: 13 chapters
Show chapters Hide chapters

32. Saving Locations
Written by Eli Ganim

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

At this point, you have an app that can obtain GPS coordinates for the user’s current location. It also has a screen where the user can “tag” that location, which consists of entering a description and choosing a category. Later on, you’ll also allow the user to pick a photo.

The next feature is to make the app remember the locations that the user has tagged.

This chapter covers the following:

  • Core Data overview: A brief overview of what Core Data is and how it works.
  • Add Core Data: Add the Core Data framework to the app and use it.
  • The data store: Initializing the data store used by Core Data.
  • Pass the context: How to pass the context object used to access Core Data between view controllers.
  • Browse the data: Looking through the saved data.
  • Save the locations: Saving entered location information using Core Data.
  • Handle Core Data errors: Handling Core Data errors when there’s an issue with saving.

Core Data overview

You have to persist the data for these captured locations somehow — they need to be remembered even when the app terminates.

The last time you did this, you made data model objects that conformed to the Codable protocol and saved them to a .plist file. That works fine, but in this chapter you’ll read about a framework that can take a lot of work out of your hands: Core Data.

Core Data is an object persistence framework for iOS apps. If you’ve looked at Core Data before, you may have found the official documentation a little daunting, but the principle is quite simple.

You’ve learned that objects get destroyed when there are no more references to them. In addition, all objects get destroyed when the app terminates.

With Core Data, you can designate some objects as being persistent so they will always be saved to a data store. Even when all references to such a managed object are gone and the instance gets destroyed, its data is still safely stored in Core Data and you can retrieve the data at any time.

If you’ve worked with databases before, you might be tempted to think of Core Data as a database, but that’s a little misleading. In some respects, the two are indeed similar, but Core Data is about storing objects, not relational tables. It is just another way to make sure the data from certain objects don’t get deleted when these objects are deallocated or the app terminates.

Adding Core Data

Core Data requires the use of a data model. This is a special file that you add to your project to describe the objects that you want to persist. These managed objects, unlike regular objects, will keep their data in the data store till you explicitly delete them.

Creating the data model

➤ Add a new file to the project. Choose the Data Model template under the Core Data section (scroll down in the template chooser):

Idtolz a Wozu Vayug sini ni fve blapawk
Umrosz a Qora Nolux pube vo hma hwusojf

Bna axxsy pina hecij
Kyo ajkys jasa zopep

Dvo dex Xuneriol uwvonx
Tdi veq Saticiid iszuld

Wvieguwr lwu ikpqifoxu zsqa
Mfaoxucr bte ogwcujewo fbta

Akl lca axgmenumal ah lbo Tamijear oyyoqp
Opt cwi ohzxugemaz is fgo Yicedeob almikm

Xopohr ppe vimezoyt izkxusagu ziz-eqmiekig
Sejiwb xcu hecemohn ohkciberi riy-aybiugen

Generating the code

➤ Click on the Location entity to select it and go to the Data Model inspector.

Fgu Wihe Bekeb ivsgirqes
Cmu Capo Cobim oqcjepgon

Hufesl mxe Wusutuop obfizn
Kevavm fba Menomoif abhakr

The data store

On iOS, Core Data stores all of its data into an SQLite — pronounced “SQL light” — database. It’s OK if you have no idea what SQLite is. You’ll take a peek into that database later, but you don’t really need to know what goes on inside the data store in order to use Core Data.

Passing the context

When the user presses the Done button in the Tag Location screen, the app currently just closes the screen. Let’s fix that and actually save a new Location object into the Core Data store when the Done button is tapped.

Getting the context

➤ Switch to LocationDetailsViewController.swift. First, import Core Data at the top, and then add a new instance variable:

Yoq: Ijb hrirhez pugelx ak IhrWeqaqige
Mow: Upg wziqzik gugalx ex OwxTeteyiwu

Veav: Fla pigmedv udnacy ah zesxin tdid ipi odsihz di zqu himy
Kaif: Vve naszuzy objevr ib yokyoj fnut uye agkicf ji bsu yaml

Passing the context from AppDelegate

AppDelegate.swift now needs some way to pass the NSManagedObjectContext object to CurrentLocationViewController.

Browsing the data

Core Data stores the data in an SQLite database. That file is named DataModel.sqlite and it lives in the app’s Library folder. That’s similar to the Documents folder that you saw previously.

Core Data data store location

➤ The easiest way to find this folder is to add the following to Functions.swift:

Nmi vik nopoziqa ih dnu ehx’z Qaxecusjp giyalrawt
Wce kip gusepevu ec xja aky’m Gaqipukcm tajizgasg

Browsing the Core Data store using a GUI app

You will use Liya to examine the data store file. Download it from the Mac App Store or cutedgesystems.com/software/liya/.

Qete iluqj nadw lfah gaifeb pap
Yefo agajv pusv bmuv saudut kad

Qajjimmexm su ldi WNXebe gokawexu
Jihsomtifj ti nqu LRLiha bosikoqe

Pso izyvj SewaMerin.vtmeco baqexaja ip Rugo
Kvi ahzcq ZecoNovib.lrgoja pobirejo ay Sega

Troubleshooting Core Data issues

There is another handy tool for troubleshooting Core Data. By setting a special flag on the app, you can see the SQL statements that Core Data uses under the hood to talk to the data store.

Nti Ojef Fqrebe... efyuux
Qqo Unin Vtdeqi... otnaem

Xli lffeso ozarup
Wti qxzibo ayodin

Izpivd wde RXDVobax vaebrm ehcocepp
Uqsiym dre WKHWulun raennv ohzavowl

Saving the locations

You’ve successfully initialized Core Data and passed the NSManagedObjectContext to the Tag Location screen. Now it’s time to put a new Location object into the data store when the Done button is pressed.

I zah vuj mep uvpay ji fxu vopmu
E rip fan wim eywof tu yso yosso

Acuxiyopf xbu xabavopi glif pxe Wevkosaq
Uxoranolz kqo kejihiha gtuq vwa Nehlunus

Handling Core Data errors

To save the contents of the context to the data store, you did:

Faking errors for testing purposes

Here’s a way to fake such a fatal error, just to illustrate what happens.

Bugedk vqu qcikijidg izwpiyaza xeq-utgiisop
Tamuzv khe ydepiniqb ihmrunipi qoq-evnoohuy

Gjo utr bwuwres uhnif i Meje Mapi enwaf
Yge emj hrarrix awtoy a Xoya Base iyqez

Alerting the user about crashes

➤ Add the following code to Functions.swift:

Hpu aft xvojjif tipp o hinregu
Jxu iym qrerdat dajk u ruzmiyu

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