In the previous chapter, entitled Working with iOS 17 Databases using Core Data, an overview of the Core Data stack was provided, together with details of how to write code to implement data persistence using this infrastructure. In this chapter, we will continue to look at Core Data in a step-by-step tutorial that implements data persistence using Core Data in an iOS 17 app.
The Core Data Example App
The app developed in this chapter will take the form of the same contact database app used in previous chapters, the objective being to allow the user to enter their name, address, and phone number information into a database and then search for specific contacts based on the contact’s name.
Creating a Core Data-based App
As is often the case, we can rely on Xcode to do much of the preparatory work for us when developing an iOS app that will use Core Data. To create the example app project, launch Xcode and select the option to create a new project. In the new project window, select the iOS App project template. In the next screen, ensure the Swift and Storyboard options are selected. Next, enter CoreDataDemo into the Product Name field, enable the Use Core Data checkbox, and click Next to select a location to store the project files.
Xcode will create the new project and display the main project window. In addition to the usual files that are present when creating a new project, an additional file named CoreDataDemo.xcdatamodeld is also created. This is the file where the entity descriptions for our data model will be stored.
Creating the Entity Description
The entity description defines the model for our data, much like a schema defines the model of a database table. To create the entity for the Core Data app, select the CoreDataDemo.xcdatamodeld file to load the entity editor:
To create a new entity, click the Add Entity button in the bottom panel. Double-click on the new Entity item beneath the Entities heading and change the entity name to Contacts. With the entity created, the next step is to add some attributes that represent the data that is to be stored. To do so, click on the Add Attribute button. In the Attribute pane, name the attribute name and set the Type to String. Repeat these steps to add two other String attributes named address and phone, respectively:
Designing the User Interface
With the entity defined, now is a good time to design the user interface and establish the outlet and action connections. Select the Main.storyboard file to begin the design work. The user interface and corresponding connections used in this tutorial are the same as those in previous data persistence chapters. The completed view should, once again, appear as outlined in Figure 49-3 (note that objects may be cut and pasted from the previous Database project to save time in designing the user interface layout):
Before proceeding, stretch the status label (located above the two buttons) so that it covers most of the width of the view and configure the alignment attribute so that the text is centered. Finally, edit the label and remove the word “Label” so it is blank.
Select the topmost text field object in the view canvas, display the Assistant Editor panel, and verify that the editor displays the contents of the ViewController.swift file. Next, ctrl-click on the text field object again and drag it to a position just below the class declaration line in the Assistant Editor. Release the line, and in the resulting connection dialog, establish an outlet connection named name.
Repeat the above steps to establish outlet connections for the remaining text fields and the label object to properties named address, phone, and status, respectively.
Ctrl-click on the Save button object and drag the line to the area immediately beneath the viewDidLoad method in the Assistant Editor panel. Release the line and, within the resulting connection dialog, establish an Action method on the Touch Up Inside event configured to call a method named saveContact. Repeat this step to create an action connection from the Find button to a method named findContact.
Initializing the Persistent Container
The next step in this project is to initialize the Core Data stack and obtain a reference to the managed object context. Begin by editing the ViewController.swift file to import the Core Data framework and to declare a variable in which to store a reference to the managed object context object:
override func viewDidLoad() {
super.viewDidLoad()
initCoreStack()
}
func initCoreStack() {
let container = NSPersistentContainer(name: "CoreDataDemo")
container.loadPersistentStores(completionHandler: {
(description, error) in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
} else {
self.managedObjectContext = container.viewContext
}
})
}
.
.
Code language: Swift (swift)
Saving Data to the Persistent Store using Core Data
When the user touches the Save button, the saveContact method is called. Therefore, within this method, we must implement the code to create and store managed objects containing the data entered by the user. Select the ViewController.swift file, scroll down to the template saveContact method, and implement the code as follows:
@IBAction func saveContact(_ sender: Any) {
if let context = managedObjectContext, let entityDescription =
NSEntityDescription.entity(forEntityName: "Contacts",
in: context) {
let contact = Contacts(entity: entityDescription,
insertInto: managedObjectContext)
contact.name = name.text
contact.address = address.text
contact.phone = phone.text
do {
try managedObjectContext?.save()
name.text = ""
address.text = ""
phone.text = ""
status.text = "Contact Saved"
} catch let error {
status.text = error.localizedDescription
}
}
}
Code language: Swift (swift)
The above code uses the managed object context to obtain the Contacts entity description and then uses it to create a new instance of the Contacts managed object subclass. This managed object’s name, address, and phone attribute values are then set to the current text field values. Finally, the context is instructed to save the changes to the persistent store with a call to the context’s save method. The success or otherwise of the operation is reported on the status label, and in the case of a successful outcome, the text fields are cleared and ready for the next contact to be entered.
Retrieving Data from the Persistent Store using Core Data
To allow the user to search for a contact, implementing the findContact action method is now necessary. As with the save method, this method will need to identify the entity description for the Contacts entity and then create a predicate to ensure that only objects with the name specified by the user are retrieved from the store. Matching objects are placed in an array from which the attributes for the first match are retrieved using the value(forKey:) method and displayed to the user. A full count of the matches is displayed in the status field. The code to perform these tasks is as follows:
@IBAction func findContact(_ sender: Any) {
if let context = managedObjectContext {
let entityDescription =
NSEntityDescription.entity(forEntityName: "Contacts",
in: context)
let request: NSFetchRequest<Contacts> = Contacts.fetchRequest()
request.entity = entityDescription
if let name = name.text {
let pred = NSPredicate(format: "(name = %@)", name)
request.predicate = pred
}
do {
let results =
try context.fetch(request as!
NSFetchRequest<NSFetchRequestResult>)
if results.count > 0 {
let match = results[0] as! NSManagedObject
name.text = match.value(forKey: "name") as? String
address.text = match.value(forKey: "address") as? String
phone.text = match.value(forKey: "phone") as? String
status.text = "Matches found: \(results.count)"
} else {
status.text = "No Match"
}
} catch let error {
status.text = error.localizedDescription
}
}
}
Code language: Swift (swift)
Building and Running the Example App
The final step is to build and run the app. Click on the run button located in the toolbar of the main Xcode project window. If errors are reported, check the syntax of the code you have written using the error messages provided by Xcode as guidance. Once the app compiles, it will launch and load into the device or iOS Simulator. Next, enter some test contacts (some with the same name). Having entered some test data, enter the name of the contact for which you created duplicate records and tap the Find button. The address and phone number of the first matching record should appear together with an indication in the status field of the total number of matching objects retrieved.
Summary
The Core Data Framework provides an abstract, object-oriented interface to database storage within iOS apps. As demonstrated in the example app created in this chapter, Core Data does not require any knowledge of the underlying database system. Combined with Xcode’s visual entity creation features, it allows database storage to be implemented relatively easily.