Core Data Flashcards

1
Q

Technical answer what is Core Data

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Technical answer what is Core Data

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is NSPersistentContainer?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What managed object model

A

describes the way Core Data represents data on disk.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is entity in coreData?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is attribute in coreData?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is relationship in coreData?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What NSManagedObject represents?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is KVC

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Way Core Data provides to read the value

A

The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Saving to Core Data

A
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)”)
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Fetching from Core Data step by step

A

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. 
  1. 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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What persistence Core Data provides?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Data Model editor what is?

A

you can use to create your managed object model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

For what you need NSManagedObjectContext?

A

You need an NSManagedObjectContext to save() or fetch(_:) data to and from Core Data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What Subclassing NSManagedObject do?

A

This creates a direct one-to-one mapping between entities in the data model editor and classes in your code. This means in some parts of your code, you can work with objects and properties without worrying too much about the Core Data side of things.

17
Q

Storing non-standard data types in Core Data

A

You can save any data type to Core Data (even ones you define) using the Transformable
type as long as your type conforms to the NSCoding protocol.
Note:The NSCoding protocol (not to be confused with Swift’s Codable protocol) is a simple way to archive and unarchive objects that descend

18
Q

The best alternative to key-value coding (CoreData)

A

create NSManagedObject subclasses for each entity in your data model. That means there will be a Bowtie class with correct types for each property.

19
Q

What @NSManaged attribute informs?

A

Similar to @dynamic in Objective-C, the @NSManaged attribute informs the Swift compiler that the backing store and implementation of a property will be provided at runtime instead of compile time.
The normal pattern is for a property to be backed by an instance variable in memory. A property on a managed object is different: It’s backed by the managed object context, so the source of the data is not known at compile time.

20
Q

Core Data entities and has two main benefits:

A
  1. Managed object subclasses unleash the syntactic power of Swift properties. By accessing attributes using properties instead of key-value coding, you befriend Xcode and the compiler.
  2. You gain the ability to override existing methods or to add your own. Note there are some NSManagedObject methods you must never override. Check Apple’s documentation of NSManagedObject for a complete list.
21
Q

2 approaches in where to keep managed object context

A

a global variable in appDelegate vs pass the managed object context from class to class via a property.

22
Q

CoreData have its own errors?

A

Yes, you check them in do-catch block

When an NSError is involved, it’s standard practice to check the domain and code for the error to determine what went wrong

23
Q

attribute data types in coreData

A

Core Data supports different attribute data types, which determines the kind of data you can store in your entities and how much space they will occupy on disk. Some common attribute data types are String, Date, and Double.

24
Q

The Binary Data attribute data type

A

The Binary Data attribute data type gives you the option of storing arbitrary amounts of binary data in your data model.

25
Q

The Transformable attribute data type

A

The Transformable attribute data type lets you store any object that conforms to NSCoding in your data model.

26
Q

Using an NSManagedObject subclassis a better way

A

Using an NSManagedObject subclassis a better way to work with a Core Data entity. You can either generate the subclass manually or let Xcode do it automatically.

27
Q

You can refine the set entities fetched by

A

NSFetchRequest using an NSPredicate.

28
Q

validation rules in coreData

A

You can set validation rules (e.g. maximum value and minimum value) to most attribute data types directly in the data model editor. The managed object context will throw an error if you try to save invalid data.

29
Q

The Core Data Stack

A

The stack is made up of four Core Data classes:

  • NSManagedObjectModel
  • NSPersistentStore
  • NSPersistentStoreCoordinator
  • NSManagedObjectContext
30
Q

What is the managed object model?

A

The NSManagedObjectModel represents each object type in your app’s data model, the properties they can have, and the relationships between them. Other parts of the Core Data stack use the model to create objects, store properties and save data.
As mentioned earlier in the book, it can be helpful to think about NSManagedObjectModel as a database schema. If your Core Data stack uses SQLite under the hood, NSManagedObjectModel represents the schema for the database.
However, SQLite is only one of many persistent store types you can use in Core Data (more on this later), so it’s better to think of the managed object model in more general terms.

Note: You may be wondering how NSManagedObjectModel relates to the data model editor you’ve been using all along. Good question!
The visual editor creates and edits an xcdatamodelfile. There’s a special compiler, momc, that compiles the model file into a set of files in a momdfolder.
Just as your Swift code is compiled and optimized so it can run on a device, the compiled model can be accessed efficiently at runtime. Core Data uses the compiled contents of the momdfolder to initialize an NSManagedObjectModel at runtime.

31
Q

The persistent store

A

NSPersistentStore reads and writes data to whichever storage method you’ve decided to use. Core Data provides four types of NSPersistentStore out of the box: three atomic and one non-atomic.

32
Q

Atomic and non-atomic Persistent Store

A

An atomic persistent store needs to be completely deserialized and loaded into memory before you can make any read or write operations. In contrast, a non-atomicpersistent store can load chunks of itself onto memory as needed.

33
Q

Core Data store types

A
  1. NSQLiteStoreTypeis backed by an SQLite database. It’s the only non-atomic store type Core Data supports out of the box, giving it a lightweight and efficient memory footprint. This makes it the best choice for most iOS projects. Xcode’s Core Data template uses this store type by default.
  2. NSXMLStoreTypeis backed by an XML file, making it the most human-readable of all the store types. This store type is atomic, so it can have a large memory footprint. NSXMLStoreType is only available on OS X.
  3. NSBinaryStoreTypeis backed by a binary data file. Like NSXMLStoreType, it’s also an atomic store, so the entire binary file must be loaded onto memory before you can do anything with it. You’ll rarely find this type of persistent store in real-world applications.
  4. NSInMemoryStoreTypeis the in-memory persistent store type. In a way, this store type is not really /persistent/. Terminate the app or turn off your phone, and the data stored in an in-memory store type disappears into thin air. Although this may seem to defeat the purpose of Core Data, in-memory persistent stores can be helpful for unit testing and some types of caching.

Note: Were you holding your breath for a persistent store type backed by a JSON file or a CSV file? Bummer. The good news is you can create your own type of persistent store by subclassing NSIncrementalStore.

34
Q

The persistent store coordinator

A

NSPersistentStoreCoordinator is the bridge between the managed object model and the persistent store. It’s responsible for using the model and the persistent stores to do most of the hard work in Core Data. It understands the NSManagedObjectModel and knows how to send information to, and fetch information from, the NSPersistentStore.

35
Q

NSPersistentStoreCoordinator hides the implementation details of how your
persistent store or stores are configured. This is useful for two reasons:

A
  1. NSManagedObjectContext (coming next!) doesn’t have to know if it’s saving to an SQLite database, XML file or even a custom incremental store.
  2. If you have multiple persistent stores, the persistent store coordinator presents a unified interface to the managed context. As far as the managed context is concerned, it always interacts with a single, aggregate persistent store.
36
Q

The managed object context

A

On a day-to-day basis, you’ll work with NSManagedObjectContext the most out of the four stack components. You’ll probably only see the other three components when you need to do something more advanced with Core Data.

objects.
* You do all of the work with your Core Data objects within a managed object context.

  • Any changes you make won’t affect the underlying data on disk until you call save() on the context.
  1. The context /manages/the lifecycle of the objects it creates or fetches. This lifecycle management includes powerful features such as faulting, inverse relationship handling and validation.
3. A managed object cannot exist without an associated context. In fact, a managed object and its context are so tightly coupled that every managed object keeps a reference to its context, which can be accessed like so: 
`let managedContext = employee.managedObjectContext`
  1. Contexts are very territorial; once a managed object has associated with a particular context, it will remain associated with the same context for the duration of its lifecycle.
  2. An application can use more than one context — most non-trivial Core Data applications fall into this category. Since a context is an in-memory scratch pad for what’s on disk, you can actually load the same Core Data object onto two different contexts simultaneously.
  3. A context is not thread-safe. The same goes for a managed object: You can only interact with contexts and managed objects on the same thread in which they were created.