Timering

Purp

“You must to know!” Collection - Core Data simple explanations

With Core Data framework you can manage your objects in your App. You can manage your object’s life-cycle and object graph, so the attributes and relationships of your entities. You can edit, save modify and rebuild your database. You can group, filtering, organizing your data. I try to explain just the basics with this example.

I’m going to create a model with users who have listed some types (family, classmates, friends, love), and they have various hobbies.

In our model a user can belong to only one type, but one type can contain multiple users. For example, the family type may contain brother, mother, and father as well. But Father user cannot be in the type of “classmates” if it belongs to already “family” type.

Chapters

  1. ManagedObject, ManagedObjectModel and ManagedObjectContext
  2. PersistentStoreCoordinator
  3. Relationships
  4. Delete Rules
  5. Fetch Request, NSPredicate and NSSortDescriptor

Part of the series:

  1. Core Data tutorial Part 1 / 5 - Create Managed Object Model with Attributes, Relationships & Delete Rules
  2. Core Data tutorial Part 2 / 5 - Save Entity’s Attributes, Relationships, and make FetchRequest
  3. Core Data tutorial Part 3 / 5 - Edit, Delete NSManagedObjects
  4. Core Data part 4 / 5 - Change Core Data model, using SortDescriptor, NSPredicate FetchRequest and filter Array using Predicate
  5. Core Data tutorial part 4.2 / 5 - Using NSFetchedResultsController, Reorder TableViewCells with LongPressGesture
  6. CoreData Tutorial Part 5/5 - Model Versioning, Lightweight Migration, Model Mapping

iCloud Sync tutorials:

  1. iCloud Sync tutorial Part 1/2 - create iCloudStore, check if user is Signed in, migrate store
  2. iCloud Sync tutorial Part 2/2 - soon!

1. ManagedObject, ManagedObjectModel and ManagedObjectContext

First you need to describe your objects or entities, so you have to create a schema, which can tell what is the property or name or class, and which attributes can you use to describe your object, which belongs to an array. This schema will be the Managed Object Model. For example:

SpotlessiCode | IOS Tutorial | Core Data | Must to know_1

Entity Description:

  • Name: “User”
  • Classname: “User”
  • Property: array

The array property consists collection of attributes and relationships. 

Example:

Attribute ————— collection

  • Name: “userName”
  • Type: “string”
  • ValueClass: “NSString”

Attribute ————— collection

  • Name: “userBirthDate
  • Type: “date”
  • ValueClass: “NSDate”

Relationship ————— collection

  • Name: “typeofuser”
  • Destination Entity: Type

More info about Managed Object Model in Developer Library.

The ManagedObjectContext is the place or space, her you can manage your collections of managed objects. You can do any modification with your objects and relationships in the same context, so you can manage and follow their life cycle.
More info about ManagedObjectContext in Developer Library.

Probably you will find these line there:

2. PersistentStoreCoordinator

Developer Library gives you a very clear explanation:

“A persistent store coordinator associates persistent object stores and a managed object model, and presents a facade to managed object contexts such that a group of persistent stores appears as a single aggregate store. A persistent store coordinator is an instance of NSPersistentStoreCoordinator. It has a reference to a managed object model that describes the entities in the store or stores it manages.

The coordinator is the central object in a Core Data stack. In many applications you just have a single store, but in complex applications there may be several, each potentially containing different entities. The persistent store coordinator’s role is to manage these stores and present to its managed object contexts the facade of a single unified store. When you fetch records, Core Data retrieves results from all of them, unless you specify which store you’re interested in.” Source

3. Relationships

In our example, we have one type with more users, so this will be a one to many, so “to-many” relationship. We can call this relationship “usersoftype”, which located at Type Entity, but the Destination is User Entity.

SpotlessiCode | IOS Tutorial | Core Data | Must to know 3_1

It has an Inverse because we have more users with one type, so this relationship from this side will be “to-one”. And we can call “typeofuser” which belongs to User Entity, but the Destination will be “Type” because the connection end/belongs at/to “Type” Entity.

SpotlessiCode | IOS Tutorial | Core Data | Must to know 3_2

You can see in Xcode the Core Data model in Graph Editor Style, and you can check yourself:

SpotlessiCode | IOS Tutorial | Core Data | Must to know 3_3

"You can specify a relationship as being to-one or to-many. To-one relationships are represented by a reference to the destination object. To-many relationships are represented by mutable sets (although fetched properties are represented by arrays). Implicitly, “to-one” and “to-many” typically refer to “one-to-one” and “one-to-many” relationships respectively. A many-to-many relationship is one where a relationship and its inverse are both to-many. These present some additional considerations, and are discussed in greater detail in Many-to-Many Relationships.” Source Core Data Relationships

Probably you will find these line there:

4. Delete Rules

We have Type Entity and User Entity, and we have usersoftype and typeofuser relationships. When you do the settings, this will look like this:

User Entity

  • Relationship: “typeofuser”
  • Destination: “Type”
  • Type: “To One”
  • Delete Rule: “Nullify”

In this case, we just tell to the destination object “null”, when the object deleted.

Type Entity

  • Relationship “usersoftype”
  • Destination: “User”
  • Type: “To Many”
  • Delete Rule: “Cascade”

In this case if you delete this type (family), you automatically delete all users, which belongs to this type (brother, mother, father).

"Relationship Delete Rules

A relationship’s delete rule specifies what should happen if an attempt is made to delete the source object. Note the phrasing in the previous sentence—”if an attempt is made…”. If a relationship’s delete rule is set to Deny, it is possible that the source object will not be deleted. Consider again a department’s employees relationship, and the effect that the different delete rules have.

Deny

If there is at least one object at the relationship destination, then the source object cannot be deleted. For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere (or fired!) otherwise the department cannot be deleted.

Nullify

Set the inverse relationship for objects at the destination to null. For example, if you delete a department, set the department for all the current members to null. This only makes sense if the department relationship for an employee is optional, or if you ensure that you set a new department for each of the employees before the next save operation.

Cascade

Delete the objects at the destination of the relationship. For example, if you delete a department, fire all the employees in that department at the same time. No Action Do nothing to the object at the destination of the relationship. For example, if you delete a department, leave all the employees as they are, even if they still believe they belong to that department.” Delete Rules Core Data source

5. Fetch Request, NSPredicate and NSSortDescriptor

If you would like to edit, or show your objects or your object’s attribute, you should make a fetch request. You can call your Entity’s objects in an Array, and then you can work with them. You can use NSPredicate to tell in which parameters you would like to fetch your objects, and, of course, you can tell for example, that you want to order your results ascending alphabetically. You can do this with NSSortDescriptor.

"A fetch request tells a managed object context the entity of the managed objects that you want to fetch; optionally, it specifies other aspects such as constraints on the values the objects’ properties must have and the order you want the objects returned in. A fetch request is an instance of NSFetchRequest. The entity it specifies is represented by an instance of NSEntityDescription; any constraints are represented by an NSPredicate object, and the ordering by an array of one or more instances of NSSortDescriptor. These are akin to the table name, WHERE clause, and ORDER BY clauses of a database SELECT statement respectively.

You execute a fetch request by sending a message to a managed object context. The context returns an array containing the objects (if any) that matched the request.” Fetch request source

Probably you will find these line there:

6. Now you can start the Core Data tutorial

I created a series, you can learn everything in these parts!

Share & Follow

If you would like to be notified of my new solutions, please subscribe to my Newsletter or my youtube channel and/ or follow me on Facebook or Twitter! Check Footer section for these opportunities!