1. Home
  2. Explore
  3. Computer Science
  4. Core Data in Swift

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Core Data in Swift

  • 93Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Core Data Concepts

What is Core Data, and what role does it play in an application?

93 questions

  1. 1

    What is Core Data, and what role does it play in an application?

    Model answer

    Core Data is an object-oriented framework for storing and retrieving objects in a database. It lets an application work with objects and their properties rather than directly writing SQL.

    Explanation

    Core Data provides an object-oriented layer over database storage.

  2. 2

    How does Core Data relate application objects to a relational database?

    Model answer

    Core Data maps objects and their properties to tables and rows in a relational database. Xcode provides a model editor for defining this mapping.

    Explanation

    The mapping lets developers work with objects while Core Data handles the database representation.

  3. 3

    Why can a Swift developer use Core Data without knowing SQL?

    Model answer

    Core Data performs storage using a database such as SQL, but provides an object-oriented interface for creating, changing, fetching, and relating data.

    Explanation

    The framework handles the database operations behind the object-oriented API.

  4. 4

    What kinds of operations does Core Data support on stored objects?

    Model answer

    It supports creating objects, changing their property values, establishing relationships, saving changes, and fetching objects that match criteria.

    Explanation

    These operations cover the main ways an application works with persistent data.

  5. 5

    How can objects retrieved from Core Data be used in a user interface?

    Model answer

    Objects retrieved from Core Data can serve as the data source for UI elements, much like data previously held in arrays or dictionaries in view models.

    Explanation

    The interface can read the stored objects to display application data.

  6. 6

    How does Core Data support relationships between objects?

    Model answer

    Relationships are defined in the data model and can be established by assigning one object to a relationship property on another object.

    Explanation

    For example, assigning an airport as a flight’s origin creates a relationship between the flight and airport.

  7. 7

    What does it mean for Core Data to provide features beyond basic object storage?

    Model answer

    Core Data includes additional database capabilities, such as optimistic locking, beyond the object creation, relationship, save, and fetch operations introduced here.

    Explanation

    The framework has more advanced features than those needed for basic persistence.

  8. 8

    Why might an application store data in Core Data rather than rely only on in-memory collections?

    Model answer

    A database provides persistent storage, so data can remain available beyond the immediate in-memory state of the application.

    Explanation

    The lesson contrasts database storage with data held in view models and collections.

  9. 9

    What is the purpose of adding extensions to classes generated from a Core Data model?

    Model answer

    Extensions let developers add their own methods and computed properties to generated classes without changing the database-stored properties.

    Explanation

    The model generates the classes and stored properties; extensions add application-specific behavior.

  10. 10

    How do the generated Core Data classes relate to view models?

    Model answer

    Core Data objects are observable objects and can act like small, object-specific view models that provide data to the UI.

    Explanation

    Their observable nature allows views to use them as data-bearing objects.

  11. 11

    What is an entity in a Core Data model?

    Model answer

    An entity defines a kind of object that Core Data stores, such as an Airport, Airline, or Flight.

    Explanation

    Xcode uses the model’s entities to generate corresponding classes.

  12. 12

    What kinds of properties are called attributes in a Core Data entity?

    Model answer

    Attributes are the entity’s data fields, such as an airline’s code and name or a flight’s arrival time.

    Explanation

    Attributes represent values stored on individual objects.

  13. 13

    What attributes were defined for an Airline in the example model?

    Model answer

    The Airline has a code, a full name, and a short name, all stored as strings.

    Explanation

    The short name is a concise form of the airline’s full name.

  14. 14

    What airport information was represented as attributes in the example model?

    Model answer

    An Airport has an ICAO code, latitude, longitude, location, time zone, and name; the coordinates are stored as doubles.

    Explanation

    The ICAO code identifies the airport, while the other attributes describe its location and time zone.

  15. 15

    What attributes were defined for a Flight in the example model?

    Model answer

    A Flight has an identifier, aircraft, arrival time, departure time, and filed departure time. The time fields are dates.

    Explanation

    The filed departure time can describe a flight that has not yet departed.

  16. 16

    What distinguishes a flight’s filed departure time from its departure time?

    Model answer

    The filed departure time is the time the pilot has filed or requested to depart; the flight may still be on the ground and not have departed.

    Explanation

    The model therefore keeps filed departure separate from departure.

  17. 17

    What relationships does a Flight have in the example model?

    Model answer

    A Flight has relationships to its origin Airport, destination Airport, and Airline.

    Explanation

    These relationships represent the airports it travels between and the airline operating it.

  18. 18

    Why are the airport-to-flight relationships represented as to-many relationships?

    Model answer

    An airport can be the destination or origin of multiple flights, so its relationships to those flights must allow multiple related Flight objects.

    Explanation

    A single airport may serve many arriving and departing flights.

  19. 19

    What does the inverse relationship of a Flight’s destination relationship represent?

    Model answer

    It represents the set of flights arriving at that Airport, called the airport’s flights-to relationship.

    Explanation

    The inverse lets an airport provide access back to related flights.

  20. 20

    What does the inverse relationship of a Flight’s origin relationship represent?

    Model answer

    It represents the set of flights departing from that Airport, called the airport’s flights-from relationship.

    Explanation

    The relationship connects an airport to flights that use it as their origin.

  21. 21

    What relationship does an Airline have to Flight objects?

    Model answer

    An Airline has a to-many relationship to the Flights it operates.

    Explanation

    One airline can operate multiple flights.

  22. 22

    What happens to inverse relationships when one side of a Core Data relationship is assigned?

    Model answer

    Core Data maintains both sides automatically; assigning a Flight’s origin updates the Airport’s flights-from relationship, and changing the inverse side updates the Flight.

    Explanation

    Developers do not have to manually keep the two sides synchronized.

  23. 23

    What types are generated for the to-one and to-many relationships in the example?

    Model answer

    A Flight’s origin, destination, and airline are single related objects; an Airport’s flight collections and an Airline’s flight collection represent multiple Flight objects.

    Explanation

    The number of related objects determines whether a relationship is to-one or to-many.

  24. 24

    Why does Xcode’s Core Data model editor include a graphical relationship view?

    Model answer

    It allows developers to create and inspect relationships among entities graphically, in addition to defining attributes.

    Explanation

    Relationships are a central part of the object model, not just the individual properties.

  25. 25

    What does the Core Data project-creation option set up for an application?

    Model answer

    It creates a blank data model, adds code for the Core Data stack and database store, and passes a managed object context into SwiftUI’s environment.

    Explanation

    These pieces provide the model, persistent storage, and access to the database.

  26. 26

    What is the role of the persistent container in the Core Data stack?

    Model answer

    The persistent container holds the Core Data database setup and provides access to the persistent store.

    Explanation

    Application code obtains the context it needs through the container.

  27. 27

    What is an NSManagedObjectContext in Core Data?

    Model answer

    It is the context, or window, through which application code accesses objects in a database to create, fetch, and work with them.

    Explanation

    Core Data operations such as fetching and creating objects use a context.

  28. 28

    How is the managed object context made available to SwiftUI views?

    Model answer

    The context is placed in the SwiftUI environment so views can access it through the managed-object-context environment value.

    Explanation

    This avoids passing the context manually through every nested view.

  29. 29

    Why must an application pass the managed object context into a sheet or popover?

    Model answer

    A sheet or popover has a separate view environment, so the context must be added to that environment for its views and fetch requests to access the database.

    Explanation

    A child view’s inherited environment does not automatically cover a separately presented modal view.

  30. 30

    Why is the managed object context needed when creating or fetching objects?

    Model answer

    The context identifies the database access point through which Core Data creates objects and performs fetches.

    Explanation

    A context is required for operations that interact with the database.

  31. 31

    How can a Core Data object provide access to the context from which it came?

    Model answer

    A managed object knows its managed object context, so an instance method can use that context to create or fetch related data.

    Explanation

    This can avoid passing the context again when working with an existing managed object.

  32. 32

    What is the purpose of enabling CloudKit when setting up Core Data?

    Model answer

    CloudKit can mirror the database to iCloud so the user’s data can be available across their devices.

    Explanation

    CloudKit synchronization is an additional capability beyond the basic Core Data setup.

  33. 33

    Why might a developer add Core Data to a project by creating a new Core Data-enabled project and moving existing source files into it?

    Model answer

    The project-creation option supplies important Core Data setup automatically, so moving existing code into the configured project can be simpler than setting up those pieces manually.

    Explanation

    The generated setup includes the model, persistent container, and context wiring.

  34. 34

    How is a new managed object created in a database context?

    Model answer

    Create an instance of the generated entity class while supplying the managed object context, such as creating a Flight with its context.

    Explanation

    The context associates the new object with the database in which it will be stored.

  35. 35

    How are ordinary attribute values changed on a Core Data object?

    Model answer

    Set the object’s properties directly, just as with ordinary object properties; Core Data tracks those changes for persistence.

    Explanation

    For example, a Flight’s aircraft value can be assigned a string.

  36. 36

    How can a developer set a Flight’s origin to an Airport?

    Model answer

    Assign the Airport object to the Flight’s origin relationship property.

    Explanation

    The assignment establishes the relationship between those objects.

  37. 37

    Why should an application check whether an Airport already exists before creating another one for the same ICAO code?

    Model answer

    The code may already identify an Airport in the database, so looking it up first avoids creating a duplicate.

    Explanation

    The example treats an ICAO code as a unique airport identifier.

  38. 38

    How does the example obtain an Airport for a given ICAO code?

    Model answer

    It fetches an Airport matching the code and returns the existing object if found; otherwise, it creates an Airport and obtains further information from FlightAware.

    Explanation

    The lookup-and-create pattern reuses existing records when possible.

  39. 39

    Why might a newly created Airport initially contain only its ICAO code?

    Model answer

    The code is already known, while other airport information is fetched asynchronously and added later when the response arrives.

    Explanation

    The object can be returned before the external information request completes.

  40. 40

    How does the example update an Airport after receiving AirportInfo from FlightAware?

    Model answer

    It finds the Airport by its ICAO code, assigns returned values such as latitude and longitude, saves the context, and signals relevant objects to update.

    Explanation

    The update connects the asynchronous response to the corresponding stored object.

  41. 41

    How does the example update a Flight using information returned by FlightAware?

    Model answer

    It finds or creates the Flight using its identifier, updates its attributes and related Airport and Airline objects, saves the changes, and signals that the Flight changed.

    Explanation

    Flights can be updated when fresh information arrives, not just created once.

  42. 42

    Why does assigning an Airport to a Flight’s relationship also update the Airport’s related-flight collection?

    Model answer

    Core Data automatically maintains inverse relationships, so assigning one side updates the corresponding inverse side.

    Explanation

    This keeps the relationship graph consistent without manually editing both properties.

  43. 43

    What does calling context.save() accomplish?

    Model answer

    It asks Core Data to persist the changes made in that context to the database.

    Explanation

    Changes to objects must be saved to be committed to persistent storage.

  44. 44

    Why can saving a Core Data context fail?

    Model answer

    Saving can fail because of storage or other database errors, such as a full disk.

    Explanation

    The save operation can throw and therefore requires error handling.

  45. 45

    What is an NSFetchRequest used for?

    Model answer

    It describes what kind of entity to retrieve and can specify criteria and sorting for the requested objects.

    Explanation

    A fetch request tells Core Data which stored objects to return.

  46. 46

    How does a fetch request identify the entity type it should fetch?

    Model answer

    It specifies the entity, such as Flight or Airport, corresponding to an entity defined in the Core Data model.

    Explanation

    The request’s entity must match the kind of object being requested.

  47. 47

    What is an NSPredicate used for in a Core Data fetch?

    Model answer

    A predicate specifies the conditions that fetched objects must satisfy.

    Explanation

    For example, it can select flights whose arrival is before a given time and whose origin is a particular airport.

  48. 48

    What did the example predicate for previously arrived flights from San Jose require?

    Model answer

    It required the flight’s arrival to be before the current date and time and its origin to be the San Jose Airport.

    Explanation

    The predicate combines time and relationship criteria.

  49. 49

    What kinds of matching can NSPredicate support beyond equality conditions?

    Model answer

    Predicates can combine conditions and support operations such as pattern matching and begins-with tests.

    Explanation

    The predicate API can express a wide range of selection criteria.

  50. 50

    What does an NSSortDescriptor specify?

    Model answer

    It specifies a property to sort by and whether the ordering should be ascending or descending.

    Explanation

    For example, flights can be sorted by identifier or arrival time.

  51. 51

    Why are sort descriptors supplied with a fetch request?

    Model answer

    They let the database sort the results before returning them, which can be efficient, and the result is returned in the requested order.

    Explanation

    A fetch commonly returns an ordered array rather than an unordered set.

  52. 52

    Why can a fetch request use an array of sort descriptors?

    Model answer

    Multiple descriptors allow primary and secondary sorting, such as sorting by last name and then by first name.

    Explanation

    Each descriptor can provide another level of ordering.

  53. 53

    How are objects retrieved from a fetch request?

    Model answer

    Call the context’s fetch method with the request; the method returns an array of objects matching the request.

    Explanation

    The result’s element type corresponds to the entity requested.

  54. 54

    What is the difference between an empty fetch result and a failed fetch?

    Model answer

    An empty array means the fetch succeeded but found no matching objects; a failed fetch indicates an error, which may be represented as nil when using try? in the example.

    Explanation

    No matches and a database error are distinct outcomes.

  55. 55

    What does using try? with a Core Data fetch do?

    Model answer

    It attempts the throwing fetch and converts a failure into an optional nil result rather than propagating the error.

    Explanation

    The result can then distinguish a failed fetch from a successful fetch with no matches.

  56. 56

    How can a fetch request be used to look up a single Airport by ICAO code?

    Model answer

    Create an Airport fetch request with a predicate requiring the stored ICAO field to equal the supplied code, then return the first matching result if present.

    Explanation

    The ICAO code is expected to identify one airport.

  57. 57

    What does the TRUEPREDICATE predicate represent?

    Model answer

    It is a predicate that always evaluates to true, so it can be used to fetch all objects of the requested entity.

    Explanation

    The example uses it when every Airport or Airline is needed.

  58. 58

    Why should predicates and sort descriptors use the database field names rather than computed-property names?

    Model answer

    They operate on fields in the database, so they must refer to the names of the stored fields, including any renamed underlying fields.

    Explanation

    Computed properties are part of the Swift-facing interface, not necessarily database fields.

  59. 59

    What is the role of @ObservedObject when a SwiftUI view receives a Core Data object?

    Model answer

    It lets a view observe an individual Core Data object, such as a Flight, and use its properties to display data.

    Explanation

    The generated Core Data objects are observable objects.

  60. 60

    What limitation was described for relying only on @ObservedObject to reflect Core Data changes?

    Model answer

    An observed Core Data object may not automatically send a change notification when its database values change, so the code may need to call objectWillChange explicitly.

    Explanation

    The example manually signals changes after updating an object.

  61. 61

    What is @FetchRequest in SwiftUI?

    Model answer

    It is a property wrapper that runs a Core Data fetch request and supplies its results to a view.

    Explanation

    The request can be specified with an entity, predicate, and sort descriptors.

  62. 62

    How does @FetchRequest differ from a one-time fetch?

    Model answer

    It acts as a standing query that keeps its results synchronized with matching objects in the database as they are added, removed, or changed.

    Explanation

    The view does not need to manually repeat the fetch to obtain updated results.

  63. 63

    What is the type of the results supplied by a FetchRequest property?

    Model answer

    The results are a FetchedResults collection whose element type corresponds to the entity being fetched.

    Explanation

    A Flight request supplies FetchedResults of Flight objects.

  64. 64

    How can FetchedResults be used with ForEach?

    Model answer

    Because FetchedResults is a collection, it can be supplied to ForEach to create views for its elements.

    Explanation

    The fetched objects can be displayed without first converting the collection to an array.

  65. 65

    How can FetchedResults be converted to an Array, and why might that be useful?

    Model answer

    Pass the collection to the Array initializer; this is useful when array-specific operations are needed, since FetchedResults itself is a collection rather than an array.

    Explanation

    An Array can be initialized from any collection.

  66. 66

    How can a view initialize a FetchRequest when its predicate depends on an input passed to the view?

    Model answer

    Initialize the property wrapper’s backing value, such as _flights, inside the view’s initializer using a FetchRequest built with the input-dependent predicate.

    Explanation

    This allows the request to incorporate values that are unavailable at the property declaration.

  67. 67

    What happens to a SwiftUI view when its @FetchRequest results change?

    Model answer

    SwiftUI invalidates and redraws the view so it reflects the current matching data in the database.

    Explanation

    The fetch results keep the UI synchronized with the database.

  68. 68

    How can a FetchRequest be used to monitor one particular object?

    Model answer

    Use a predicate that matches the object’s unique identifier so the request tracks that single object and updates when it changes.

    Explanation

    A standing query can be useful even when only one result is expected.

  69. 69

    How should a view respond when code changes a Core Data object that it observes?

    Model answer

    The code can call the object’s objectWillChange notification so observing views redraw and reflect the updated values.

    Explanation

    The example sends this notification after wholesale updates to an Airport or Flight.

  70. 70

    How did the example make the UI’s flight list respond to new FlightAware data?

    Model answer

    It stored incoming data in Core Data and displayed flights through a FetchRequest, whose results updated as matching flights entered the database.

    Explanation

    The UI reads from the database rather than directly from the network response.

  71. 71

    Why can using @FetchRequest simplify the UI’s data-management code?

    Model answer

    The UI declares the data it needs, and the fetch results update automatically as the database changes, reducing the need for manual refetching and conditional update logic.

    Explanation

    This fits SwiftUI’s declarative approach to keeping the interface in sync with state.

  72. 72

    What was the purpose of storing FlightAware data in Core Data before building the example UI?

    Model answer

    The application loads the incoming data into a database and then builds its UI by reading from that database.

    Explanation

    This separates asynchronous data retrieval from the UI’s data source.

  73. 73

    How did replacing a string-based flight-fetching mechanism change the example’s UI data flow?

    Model answer

    The example replaced the old mechanism with Core Data objects and FetchRequests, so the UI worked with stored Flight, Airport, and Airline objects rather than string-based results.

    Explanation

    This made the data flow object-oriented and database-backed.

  74. 74

    Why did the example create Airport and Airline objects while processing incoming FlightAware flights?

    Model answer

    The FlightAware flight data identified its origin, destination, and airline with codes, so the application looked up or created the corresponding related objects.

    Explanation

    Core Data relationships connect the Flight object to Airport and Airline objects.

  75. 75

    How did the example avoid fetching unrelated flights when users selected filters?

    Model answer

    It built a predicate from the selected destination and, when present, the origin and airline, then used that predicate in the flight FetchRequest.

    Explanation

    Each selected criterion narrows the set of matching stored flights.

  76. 76

    How can a predicate be built dynamically from optional search criteria?

    Model answer

    Start with the required condition, append conditions for each optional value that exists, collect the corresponding objects as arguments, and create the predicate from the resulting format and arguments.

    Explanation

    The example adds origin and airline clauses only when those selections are present.

  77. 77

    Why can an array of different Core Data entity objects use NSManagedObject as its element type?

    Model answer

    Flight, Airport, and Airline inherit from NSManagedObject, so an array of NSManagedObject can hold instances of those different entity classes.

    Explanation

    A common superclass provides a shared type for the predicate’s arguments.

  78. 78

    How did the example populate Airport and Airline pickers from the database?

    Model answer

    It used FetchRequests with an all-matching predicate to retrieve all Airports and Airlines, then used those results as the picker choices.

    Explanation

    Because the requests remain current, newly added objects can appear in the choices.

  79. 79

    Why did the filter view need to pass its selected Airport and Airline objects rather than only their codes?

    Model answer

    The object-oriented search model represents the destination, origin, and airline as Core Data objects, allowing the predicate and UI to use those relationships directly.

    Explanation

    This replaces string-based matching with relationships between managed objects.

  80. 80

    When did the example request incoming flights for a newly selected destination?

    Model answer

    It requested incoming flights when the user completed the filter and the draft destination differed from the current destination.

    Explanation

    The check avoids fetching again when the destination has not changed.

  81. 81

    Why could the example show previously stored flights quickly after returning to a destination?

    Model answer

    The UI was reading from the database, so matching flights already stored there could appear immediately while new data continued to arrive.

    Explanation

    The database serves as the persistent local source for the interface.

  82. 82

    What is one advantage of using a database-backed data flow for network-fetched information?

    Model answer

    The UI can consistently read from the database instead of directly managing each asynchronous response, which can simplify the UI-side code.

    Explanation

    New and updated network data enters the database, and fetch results keep the display current.

  83. 83

    Why are Core Data properties often optional even when the application expects them to have values?

    Model answer

    A database object may be incomplete or corrupted, for example if object creation began but failed, so Core Data allows stored properties to be absent.

    Explanation

    Database optionality reflects the possibility that a stored value may be missing.

  84. 84

    Does the Optional setting in the Core Data model editor mean the same thing as Swift Optional?

    Model answer

    No. The model’s Optional setting describes whether a database field may be absent; it is distinct from Swift’s Optional type, even though generated properties commonly use optionals.

    Explanation

    The two concepts are related in practice but are not the same setting.

  85. 85

    How can a computed property provide a non-optional Swift-facing interface for a database field?

    Model answer

    Keep the generated stored property as the underlying optional field and add a computed property that returns a non-optional value, handling a missing value as appropriate.

    Explanation

    The computed property can hide repetitive optional checks from the rest of the application.

  86. 86

    Why did the example wrap optional database properties with computed properties?

    Model answer

    It made fields expected to be present easier to use without repeatedly checking for nil, while retaining the underlying database representation.

    Explanation

    The wrappers also provided a place to define behavior for an unexpected missing value.

  87. 87

    Why did the example wrap Core Data’s to-many relationship collections in computed properties?

    Model answer

    Core Data exposed the relationships as optional Objective-C NSSet values containing loosely typed elements, while the application wanted non-optional Swift Sets of Flight objects.

    Explanation

    The computed properties provide a cleaner, strongly typed interface.

  88. 88

    How did the example convert a Core Data NSSet relationship into a Swift Set?

    Model answer

    The computed property casts the underlying NSSet to a Swift Set of Flight objects and returns an empty Set if the stored relationship is absent.

    Explanation

    This removes both the optional collection and the loosely typed elements from normal application code.

  89. 89

    Why might an application deliberately crash if a field expected to be present is unexpectedly nil during development?

    Model answer

    A deliberate failure can expose an unexpected data-integrity condition during development so it can be investigated rather than silently hidden.

    Explanation

    The example notes that production code may need a more deliberate recovery strategy.

  90. 90

    What is a drawback of using try? for a Core Data operation in a production application?

    Model answer

    It turns failure into nil and can hide the underlying error, whereas production code may need to catch the error and decide how to handle it.

    Explanation

    Explicit error handling can provide more useful diagnostics and recovery behavior.

  91. 91

    How can a throwing context save be handled with do-catch?

    Model answer

    Place the save call in a do block, catch any error it throws, and inspect or report details such as its localized description.

    Explanation

    This makes save failures visible instead of silently discarding them.

  92. 92

    What does a Core Data error saying that the context in the environment is not connected to the persistent store coordinator indicate?

    Model answer

    It indicates that the view performing the operation does not have the correct managed object context in its environment, often because a sheet or popover was presented without passing the context.

    Explanation

    FetchRequests need an environment context to access the database.

  93. 93

    Why did the example make Airport objects Comparable and Identifiable?

    Model answer

    Those protocols let Airport objects be sorted and identified for uses such as collections, dictionaries, sets, and SwiftUI views.

    Explanation

    Comparable supplies ordering behavior, while Identifiable supplies object identity.

1 of 93
Question 1 of 93

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent