Core Data Flashcards
Technical answer what is Core Data
Core Data is an object graph management and persistence framework in the OS X and iOS SDKs.
That means Core Data can store and retrieve data, but it isn’t a relational database like MySQL or SQLite. Although it can use SQLite as the data store behind the scenes, you don’t think about Core Data in terms of tables and rows and primary ke
Technical answer what is Core Data
Core Data is an object graph management and persistence framework in the OS X and iOS SDKs.
That means Core Data can store and retrieve data, but it isn’t a relational database like MySQL or SQLite. Although it can use SQLite as the data store behind the scenes, you don’t think about Core Data in terms of tables and rows and primary keys.
What is NSPersistentContainer?
The NSPersistentContainer consists of a set of objects that facilitate saving and retrieving information from Core Data. Inside this container is an object to manage the Core Data state as a whole, an object representing the Data Model, and so on.
What managed object model
describes the way Core Data represents data on disk.
What is entity in coreData?
An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.
What is attribute in coreData?
An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name, position and salary. In a database, an attribute corresponds to a particular field in a table.
What is relationship in coreData?
A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships. For example, a Manager can have a to-many relationshipwith a set of employees, whereas an individual Employee will usually have a to-one relationshipwith his manager.
What NSManagedObject represents?
NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store. NSManagedObject is a shape-shifter. It can take the form of any entity in your Data Model, appropriating whatever attributes and relationships you defined.
An NSManagedObject is a run-time representation of a Core Data entity. You can read and write to its attributes using Key-Value Coding.
What is KVC
KVC is a mechanism in Foundation for accessing an object’s properties indirectly using strings. KVC makes NSMangedObject behave somewhat like a dictionary at runtime.
Key-value coding is available to all classes inheriting from NSObject, including NSManagedObject. You can’t access properties using KVC on a Swift object that doesn’t descend from NSObject.
Way Core Data provides to read the value
The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.
Saving to Core Data
1. Before you can save or retrieve anything from your Core Data store, you first need to get your hands on an NSManagedObjectContext. You can consider a managed object context as an in-memory "scratchpad" for working with managed objects. Think of saving a new managed object to Core Data as a two-step process: first, you insert a new managed object into a managed object context; once you're happy, you "commit" the changes in your managed object context to save it to disk. Xcode has already generated a managed object context as part of the new project's template. Remember, this only happens if you check the Use Core Datacheckbox at the beginning. This default managed object context lives as a property of the NSPersistentContainer in the application delegate. To access it, you first get a reference to the app delegate. 2. You create a new managed object and insert it into the managed object context. You can do this in one step with NSManagedObject's static method: entity(forEntityName:in:). You may be wondering what an NSEntityDescription is all about. Recall earlier, NSManagedObject was called a shape-shifter class because it can represent any entity. An entity description is the piece linking the entity definition from your Data Model with an instance of NSManagedObject at runtime. 3. With an NSManagedObject in hand, you set the name attribute using key-value coding. You must spell the KVC key (name in this case) exactly as it appears in your Data Model, otherwise, your app will crash at runtime. 4. You commit your changes to person and save to disk by calling save on the managed object context. Note save can throw an error, which is why you call it using the try keyword within a do-catch block. Finally, insert the new managed object into the people array so it shows up when the table view reloads.
~~~
func save(name: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext =
appDelegate.persistentContainer.viewContext
// 2
let entity =
NSEntityDescription.entity(forEntityName: “Person”,
in: managedContext)!
let person = NSManagedObject(entity: entity,
insertInto: managedContext)
person.setValue(name, forKeyPath: “name”)
// 4
do {
try managedContext.save()
people.append(person)
} catch let error as NSError {
print(“Could not save. (error), (error.userInfo)”)
}
}
Fetching from Core Data step by step
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
//2
let fetchRequest =
NSFetchRequest(entityName: “Person”)
//3
do {
people = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print(“Could not fetch. (error), (error.userInfo)”)
}
}
Step by step, this is what the code does:
1. Before you can do anything with Core Data, you need a managed object context. Fetching is no different! Like before, you pull up the application delegate and grab a reference to its persistent container to get your hands on its NSManagedObjectContext.
2. As the name suggests, NSFetchRequest is the class responsible for fetching from Core Data. Fetch requests are both powerful and flexible. You can use fetch requests to fetch a set of objects meeting the provided criteria (i.e. give me all employees living in Wisconsin and have been with the company at least three years), individual values (i.e. give me the longest name in the database) and more. Fetch requests have several qualifiers used to refine the set of results returned. You'll learn more about these qualifiers in Chapter 4, "Intermediate Fetching"; for now, you should know NSEntityDescription is one of these required qualifiers. Setting a fetch request's entity property, or alternatively initializing it with init(entityName:), fetches /all/objects of a particular entity. This is what you do here to fetch all Person entities. Also note NSFetchRequest is a generic type. This use of generics specifies a fetch request's /expected/return type, in this case NSManagedObject.
- You hand the fetch request over to the managed object context to do the heavy lifting. fetch(_:) returns an array of managed objects meeting the criteria specified by the fetch request.
Note: Like save(), fetch(_:) can also throw an error so you have to use it within a do block. If an error occurred during the fetch, you can inspect the error inside the catch block and respond appropriately.
Note: There were a few rough edges in this sample app: you had to get the managed object context from the app delegate each time, and you used KVC to access an entity’s attributes rather than a more natural object-style person.name.
There are better ways to save and fetch data from Core Data, which you’ll explore in future chapters. The purpose of doing it the “long way” here is to learn what’s going on behind the scenes!
What persistence Core Data provides?
on-disk persistence, which means your data will be accessible even after terminating your app or shutting down your device. This is different from in-memory persistence, which will only save your data as long as your app is in memory, either in the foreground or in the background.
Data Model editor what is?
you can use to create your managed object model.
For what you need NSManagedObjectContext?
You need an NSManagedObjectContext to save() or fetch(_:) data to and from Core Data.