Core Data in Swift
Core Data and SwiftUI
Core Data’s role
Core Data is an object-oriented framework for creating, storing, retrieving, and relating objects in a database. It commonly uses a relational database such as SQL behind the scenes, but application code can work with Swift objects rather than writing SQL statements.
Core Data maps the object model to the underlying database:
An entity describes a kind of object, such as
FlightorAirport.An entity’s attributes describe its stored values, such as an airport’s name or a flight’s arrival time.
Relationships describe connections between objects, such as a flight having an origin airport.
Core Data maps these objects, attributes, and relationships to the database’s tables, rows, and connections.
Xcode’s model editor lets developers define entities, attributes, and relationships graphically. Xcode can then generate the corresponding classes and database-supporting code. Those generated classes can be extended with methods and computed properties to add application-specific behavior.
This approach combines persistent storage with ordinary object-oriented programming: SwiftUI views can read from Core Data objects much as they would read from other data models.
Modeling entities, attributes, and relationships
A Core Data model describes the kinds of objects an application will store and how those objects connect. For a flight-tracking application, three useful entities are Airline, Airport, and Flight.
Airline
An airline might store:
Code: a unique or identifying string.
Name: the airline’s full name.
Short name: a shorter display name.
Flights: a to-many relationship to flights operated by that airline.
Airport
An airport might store:
ICAO code: a string identifier such as
KSFOorKSJC.Latitude and longitude: numeric values stored as
Double.Location: a city or region description.
Time zone: the airport’s local time zone.
Name: the airport’s full name.
Flights to and flights from: to-many relationships to flights arriving at or departing from the airport.
Flight
A flight might store:
Identifier: a flight identifier such as
UA475.Aircraft: a description or code for the aircraft.
Arrival and departure times: date values.
Filed departure time: the departure time filed before the flight has actually departed.
Origin and destination: relationships to
Airportobjects.Airline: a relationship to an
Airlineobject.
Relationship direction and cardinality
Relationships can be viewed from both ends. A flight’s origin relationship points to one airport; from that airport’s perspective, flightsFrom points to many flights. Similarly, a flight’s destination points to one airport, while the airport’s flightsTo relationship points to many flights.
In the model editor, these relationships should be configured as inverse relationships. Core Data then maintains both sides automatically. Setting a flight’s destination airport also updates that airport’s collection of incoming flights; adding the flight through the airport’s inverse relationship updates the flight’s destination.
A to-many relationship is represented as a collection. In the demonstrated Core Data model, these collections may be generated using Objective-C’s NSSet rather than Swift’s native Set, which can make the generated interface less convenient.
Setting up Core Data
The simplest setup is to enable Use Core Data when creating an application project. Xcode creates a starter data model and adds code that configures the persistent store.
Persistent container and managed object context
The persistent container manages the database store. A managed object context is the application’s working interface to that store: creating objects, fetching objects, and saving changes are performed through a context.
The standard setup makes the context available to SwiftUI through the environment:
The application obtains the context from its persistent container.
The context is added to the SwiftUI environment.
Views that need Core Data read the context from their environment.
Views within the same view hierarchy inherit the environment. A sheet or popover creates a separate presentation hierarchy, however, so its environment may need to be supplied explicitly. If a sheet uses @FetchRequest, it needs access to the same managed object context as the rest of the application.
CloudKit integration can be enabled as an additional option to mirror stored data through iCloud, but it is separate from the basic Core Data workflow.
Creating, changing, and saving objects
An object is created in a particular managed object context. The context identifies the database in which that object is managed. After creation, the object’s attributes and relationships can be set like ordinary properties.
For example, a newly created flight can have its aircraft value assigned, and its origin can be set to an Airport object. Assigning that relationship updates the inverse relationship as well.
Changes are generally committed to persistent storage by saving the context. Saving can fail—for example, because storage is unavailable—so the operation can throw an error. A simple application may use try? when failure does not need to be handled locally, but production code should consider an explicit do–catch path and decide how to report or recover from the error.
An object’s context can also be useful after the object has been fetched. A managed object knows the context that manages it, so instance methods can use that context for related fetches or object creation without requiring the context to be passed through every call.
Fetching objects with NSFetchRequest
A fetch request describes which objects Core Data should retrieve. It is parameterized by the entity type being fetched and can specify filtering and sorting.
Predicates
A predicate defines the conditions that returned objects must satisfy. Predicates can express comparisons and combine conditions with logical operators. For example, a flight search could ask for flights whose arrival time is before the current time and whose origin is a particular airport.
Predicates use the names of stored model attributes and relationships. In a design where generated storage properties are given underscore-suffixed names, predicates still need to refer to the stored database-field names, not to custom computed properties added in Swift.
Predicates support more than simple equality. They can combine conditions and provide richer matching, such as pattern-based searches. Their format-based syntax predates Swift and can feel less idiomatic than ordinary Swift code, but it is flexible.
Sort descriptors
A fetch request can include an array of sort descriptors. Each descriptor specifies a property to sort by and whether the ordering is ascending or descending. Multiple descriptors can be used for primary and secondary ordering, such as sorting people by last name and then first name.
The results are returned as an ordered array. Specifying sorting in the request lets the database perform the sort, which is often more efficient than fetching unsorted results and sorting them afterward.
Handling fetch outcomes
A fetch can fail, so it can throw an error. When a fetch is attempted with try?, the result is optional:
nilindicates that the fetch failed.An empty array indicates that the fetch succeeded but found no matching objects.
A nonempty array contains the matching managed objects.
These outcomes should not be confused: “no match” is a valid fetch result, while nil represents an error in this error-handling pattern.
Using Core Data objects in SwiftUI
Core Data integrates with SwiftUI through managed objects and property wrappers. In the demonstrated approach, entities such as Flight, Airport, and Airline behave as observable objects.
@ObservedObject for an individual object
A view can observe one managed object using @ObservedObject. The view can then read properties from it directly—for example, displaying a flight’s identifier or its related airline’s name.
This makes a Core Data object act somewhat like a small view model. When the object publishes a change, SwiftUI can redraw views that observe it. In the demonstrated implementation, a substantial programmatic update may require explicitly sending objectWillChange so that observers are notified.
@FetchRequest for matching collections
A @FetchRequest performs a fetch and exposes the results to a view as FetchedResults<Entity>. This is a collection of managed objects, so it can be used with collection-based view components such as ForEach. It can also be converted to an array when needed or processed with collection operations such as sorted.
Unlike a one-time fetch, @FetchRequest acts as a standing query. It tracks objects matching its criteria and updates its results when relevant objects are added, removed, or changed. If a changed object now satisfies the predicate, it can appear in the results; if it no longer satisfies the predicate, it can disappear.
SwiftUI then updates the affected interface as the fetch results change. This makes the interface naturally reflect the database rather than requiring the view to manually request a new fetch after every change.
A fetch request can be declared directly when its criteria are fixed. If the criteria depend on a value passed into a view, the view can initialize the property wrapper’s backing storage in its initializer. This allows the predicate to be constructed from inputs such as a selected destination airport.
Making generated model classes easier to use
Core Data-generated properties are often optional because a stored object can be incomplete—for example, if it was only partly created or the persistent data is damaged. This can make application code awkward when certain values are expected to be present during normal operation.
A common strategy is to keep the generated storage property but expose a more convenient computed property in an extension. For a value that should always exist in valid application data, the computed property can provide a nonoptional interface. The application should still consider what to do if the stored value is unexpectedly missing; simply force-unwrapping it will cause a crash.
The same technique can improve to-many relationship properties. A generated relationship may be an optional NSSet containing broadly typed objects. An extension can expose a Swift Set<Flight> instead:
The getter converts the generated set to a Swift set and can return an empty set if the stored relationship is absent.
The setter converts the Swift set back to the generated
NSSetrepresentation.
This gives the rest of the application a cleaner, more strongly typed interface while preserving the representation expected by Core Data.
Extensions can also provide useful domain behavior, such as a friendly display name, comparison behavior for sorting, and reusable fetch-request constructors.
A key distinction is that these computed properties are an application-level convenience layer. Database operations still need to use the names of the actual stored attributes and relationships.
Example workflow: storing flight data
A flight-tracking application illustrates how Core Data can separate data retrieval from interface presentation. Rather than displaying a network response directly, the application can store data received from a service in Core Data and build its interface from the database.
Looking up or creating an airport
A lookup method such as withICAO can take an airport code and a managed object context, then:
Create a fetch request for airports whose stored ICAO code matches the requested code.
Fetch the matching airports.
Return an existing airport if one is found.
If none is found, create an airport, set its ICAO code, and request additional airport details from the external service.
When the airport is first returned, it may contain only its known code. Latitude, longitude, name, and other details may arrive later because the network request is asynchronous. Code that uses the airport must therefore tolerate those fields being unavailable until the update completes.
When the response arrives, the application can look up the same airport again by its identifier, assign the returned values, save the context, and notify observers if necessary. Using an identifier to find the existing object prevents the asynchronous response from creating a duplicate.
Updating flights and related entities
Incoming flight data may include airport codes and airline codes rather than Core Data objects. Before assigning relationships, the application can use lookup-or-create methods to obtain the corresponding Airport and Airline objects.
A flight-update method can search by a stable flight identifier. If a matching flight exists, it updates that object; otherwise, it creates one. It then assigns the returned flight information and connects the flight to its origin, destination, and airline objects.
Saving the context persists these changes. Explicit error handling can be useful for this step because a failed save may indicate a serious storage problem.
Separating loading from display
The network request can run asynchronously while the interface reads from Core Data. As matching objects are inserted or updated, standing fetch requests update their results, and SwiftUI refreshes the relevant views.
This division simplifies the interface: it does not need to manage every network response directly. The database becomes the consistent source from which the displayed data is derived.
Dynamic search and filtering
A search model can hold managed objects rather than strings. For example, its destination can be an Airport, its origin can be an optional Airport, and its airline can be an Airline. This lets the application work directly with domain objects and their relationships.
A search predicate can be built from the selected values:
The destination condition is always included.
An origin condition is added if an origin has been selected.
An airline condition is added if an airline has been selected.
The predicate’s arguments can contain different managed object types by using their shared superclass, NSManagedObject. The resulting predicate can then be used by a flight fetch request.
For selection controls, separate fetch requests can retrieve all airports and all airlines. A predicate such as TRUEPREDICATE matches every object, making it useful when the application needs the complete collection. The results can be sorted for presentation, and each object can provide its own friendly display name.
When the user confirms a changed destination, the application can request incoming flights for that airport. Other filter changes can update the fetch request’s predicate so the visible results reflect the selected destination, origin, and airline.
Common integration issues and design principles
A view shows no results: The fetch may be working correctly while the database is still empty. The application must load or create the required objects.
A sheet cannot fetch data: A sheet has its own presentation environment. The managed object context must be made available to it.
A fetch returns
nil: Withtry?, this indicates a fetch error; it is different from a successful fetch that returns an empty array.A predicate refers to the wrong property: Predicates must use stored model field names, not necessarily the names of convenience properties created in extensions.
A related object is missing: External data may provide identifiers rather than managed objects. The application must fetch or create the related airport or airline before assigning the relationship.
The interface does not reflect a direct object update: In the demonstrated pattern, explicitly notify observers after substantial managed-object changes when required. For collections of matching objects,
@FetchRequestis often the more central mechanism because it tracks database changes that affect the query.
The central SwiftUI–Core Data pattern is to describe the objects a view needs with a fetch request and let the view reflect the resulting managed objects. Because the fetch results remain synchronized with the database, the interface can stay current without manually rebuilding its data whenever matching objects change.

Ask anything
We've read this whole study set, so questions about it get the best answers.