Logo for tanaschita.com

iOS developer guide on the main aspects of Core Data

Understand the main concepts of the Core Data framework.

19 Sep 2022 · 5 min read

To persist complex data structures in an iOS application, Apple provides us with the Core Data framework. Core Data allows us to store permanent data for offline use, to cache data, to add undo functionality and more.

In this developer guide, we'll look at the main concepts of Core Data.

Sponsorship logo
Using Proxyman to inspect network traffic
Proxyman is a native debugging proxy that can act as a man-in-the-middle between your application and web server. You can use its powerful toolkit to inspect network calls and debug your application on Mac, iOS Simulator, or remote devices effortlessly.
CLICK TO LEARN MORE

Core Data model

In Core Data, we define object structures by using entities that can have attributes as properties and relationships between each other.

A Core Data model is represented by a .xcdatamodeld file. Within the file, we can use Xcode's built-in editor to add entities, their attributes, define relationships and more.

Xcode's .xcdatamodeld file editor
Xcode's .xcdatamodeld file editor

Internally, the .xcdatamodeld file is an XML file. We can open it in any text editor to inspect it.

.xcdatamodeld file's XML content.
.xcdatamodeld file's XML content

Managed objects

Each entity we setup in the .xcdatamodeld file describes an object and has a corresponding class that inherits from NSManagedObject.

The NSManagedObject subclass and properties extension for the User entity might look as follows:

@objc(User)
public class User: NSManagedObject {
}
extension User {
@NSManaged public var username: String?
@NSManaged public var lastLogin: Date?
@NSManaged public var verified: Bool
@NSManaged public var posts: NSSet?
}

Each attribute has an @NSManaged annotation which indicates that Core Data dynamically provides its implementation at runtime, based on the associated entity description.

The NSManagedObject subclasses can be generated automatically or manually. Checkout this article on how to create an NSManagedObject subsclasses for Core Data entities in Xcode (coming soon) to learn more.

Managed object context

Represented by the NSManagedObjectContext type, a context has a central role in the life cycle of managed objects.

It allows us to retrieve objects from a persistent store, create new objects, delete and edit objects. These changes remain in memory until we either discard the changes or save them back to the persistent store.

let newUser = User(context: managedObjectContext)
newUser.username = ...
// setting more attributes
do {
try managedObjectContext.save()
} catch {
// handle error
}

In the example above, we create a new user and then use the save() method on the context to save the user.

Fetch requests

Represented by NSFetchRequest, we can use a fetch request to define which managed objects we want to request from the managed context.

An example to fetch all users might look like this:

let usersFetchRequest = NSFetchRequest<User>(entityName: "User")
usersFetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \User.username, ascending: true)]
do {
let users = try viewContext.execute(usersFetchRequest)
} catch {
// handle error
}

As we can see in the example above, a fetch request specifies which entity to search. Optionally, we can add a predicate to filter the results, a sort descriptor, a fetch limit and more.

When working with SwiftUI, we can use the @FetchRequest property wrapper to retrieve data from Core Data.

@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \User.username, ascending: true)])
private var users: FetchedResults<User>

Checkout this article on @FetchRequest property wrapper in SwiftUI to learn more.

NSPersistentContainer

The NSPersistentContainer class simplifies creating and managing the Core Data stack.

container = NSPersistentContainer(name: "CoreDataExampleApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
// Handle error if needed.
})

In the example above, we create an instance of NSPersistentContainer and call loadPersistentStores() on it. When successfully setup, it provides the viewContext property that gives us access to a managed object context to start working with Core Data.

Sponsorship logo
Using Proxyman to inspect network traffic
Proxyman is a native debugging proxy that can act as a man-in-the-middle between your application and web server. You can use its powerful toolkit to inspect network calls and debug your application on Mac, iOS Simulator, or remote devices effortlessly.
CLICK TO LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

core data

persistence

swift

ios

Quick guide to using Core Data with SwiftUI

Learn the basics for using the Core Data framework with SwiftUI in iOS

20 Mar 2021 · 8 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum