Core Data iOS: Designing a Data Model and Building Data Objects

0
130
7 min read

 

Core Data iOS Essentials

Core Data iOS Essentials

A fast-paced, example-driven guide guide to data-drive iPhone, iPad, and iPod Touch applications

        Read more about this book      

(For more resources on this subject, see here.)

To design data model, we need to create a new project. So, let’s start with.

Creating a new project

To create a new project, perform the following steps:

  1. Launch Xcode and create a new project by selecting the File | New Project option.
  2. The New Project Assistant window will appear, prompting us to select a template for the new project, as shown in the next screenshot. We will select the Navigation-based Application template.
  3. Ensure that the Use Core Data for storage checkbox is checked and click on the Choose… button.
  4. On selecting the Choose… button, we will get a dialog box to specify the name and the location of the project. Let us keep the location the same as default (Documents folder) and assign the project name as: prob (any name).
  5. Click on Save. Xcode will then generate the project files and the project gets opened in the Xcode project window.

The checkbox Use Core Data for storage will ask Xcode to provide all the default code that is required for using Core Data. This option is visible with only two project templates: Navigationbased Application and Window-based Application templates.

Designing the data model

Designing a data model means defining entities, attributes, and relationships for our application using a special tool. Xcode includes a data modeling tool (also known as Data Model Editor or simply a modeler) that facilitates the creation of entities, defining attributes, and the relationships among them.

Data Model Editor

The Data Model Editor is a data modeling tool provided by Xcode that makes the job of designing a data model quite easy. It displays the browser as well as a diagram view of the data model. The Browser view displays two panes, the Entity pane and the Properties pane, for defining entities and their respective properties. The diagram view displays rounded rectangles that designate entities and lines to show relationships among the entities.

Adding an entity

To add an entity to our data model, perform the following steps:

  1. Invoke the data modeling tool by double-clicking the prob.xcdatamodel file in the Resources group found in the Xcode Project window.
  2. Xcode’s data modeling tool will open and we will find that an entity by default is already created for us by the name: Event (as shown in the next image) with an attribute: timeStamp.

  3. We can delete or rename the default entity Event as desired. Let us select the default Event entity and delete it by clicking on the minus (-) button in the Entity pane followed by either choosing plus (+) button in the Entity pane or by choosing Design | Data Model | Add Entity option from the menu bar. This will add a blank entity (by the name Entity) to our data model, which we can rename as per our requirements. Let us set the name of the new entity as: Customer.

  4. Automatically, an instance of NSManagedObject will be created to represent our newly created Customer entity. The next step is to add attributes to this entity.

Adding an attribute property

We want to add three attributes by name—name, emailid, and contactno—to the Customer entity. Let’s follow the steps mentioned next for the same:

  1. Select the entity and choose the Design | Data Model | Add Attribute option from the menu bar or select the + (plus) button in the Property pane. A menu with several options such as Add Attribute, Add Fetched property, Add Relationship, and Add Fetch Request will pop up.
  2. We select the Add Attribute option from the popped up menu. We see that a new attribute property is created for our Customer entity by a default name: newAttribute in the inspector.
  3. Let us rename our new attribute as: name (as we will be using this attribute to store the names of the customers).
  4. Then, we set the type of the name attribute to String as shown in the next screenshot (as names consists of strings):

  5. Below the Name field are three checkboxes: Optional, Transient, and Indexed. Though we will be using the Optional checkbox for the name attribute, let us see the usage of all three:
    • Optional: If this checkbox is checked, it means the entity can be saved even if the attribute is nil (empty). If this checkbox is unchecked and we try to save the entity with this attribute set to nil, it will result in a validation error. When used with a relationship, if the checkbox is checked it means that the relationship can be empty. Suppose that we create one more entity say: Credit Card (where information of the customer’s credit card is kept). In that case, the relationship from customer to the credit card will be optional (we have to leave this checkbox checked) as a customer may or may not have a credit card. And if we create an entity say: Product—in that case, the relationship from the Customer to the Product cannot be empty as a customer will definitely buy at least a single product (the checkbox has to be unchecked).
    • Transient: This checkbox, if checked, means that the attribute or the relationship is of a temporary nature and we don’t want it to be stored (persist) in the persistent store. This checkbox must be unchecked for the attributes or relationship that we want to persist (to be stored on the disk).
    • Indexed: This checkbox has to be checked to apply indexing on the attribute. It is used when we want to perform sorting or searching on some attribute. By checking this checkbox, an index will be created on that attribute and the database will be ordered on that attribute.

Types of attributes

Using the Type drop-down list control, we select the data type (that is, numerical, string, date, and so on) of the attribute to specify the kind of information that can be stored in the attribute. The following is the list of data types:

  • Integer 16, Integer 32, and Integer 64 data types are for storing signed integers. The range of values that these types are able to store is as follows:
    • Integer 16:-32,768 to 32, 767
    • Integer 32:-2,147,483,648 to 2,147,483,647
    • Integer 64:-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  • Decimal, Double, and Float data types are for storing fractional numbers. The Double data type uses 64 bits to store a value while the Float data type uses 32 bits for storing a value. The only limitation with these two data types is that they round off the values. To avoid any rounding of values, the Decimal data type is preferred. The Decimal type uses fixed point numbers for storing values, so the numerical value stored in it is not rounded off.
  • String data type is used for storing text contents.
  • Boolean data type is used for storing YES or NO values.
  • Date data type is used for storing dates as well as timestamps.
  • Binary data type is used for storing binary data.
  • Transformable data type works along with Value Transformers that help us create attributes based on any Objective-C class, that is, we can create custom data types other than the standard data types. This data type can be used to store an instance of UIColor, UIImage, and so on. It archives objects to instances of NSData.

Below the Type drop-down menu, we will see a few more fields in the detail pane, as shown in the next screenshot:

Fields applying constraints

Min Length: and Max Length: fields are for applying constraints of minimum and maximum number of characters to an attribute. If we exceed the range supplied in these fields, we get a validation error. Meaning, if we enter the string of fewer characters than the value supplied in Min Length: or the string has more characters than the value supplied in Max Length: field, this will result in a validation error while saving managed objects.

Reg. Ex: field stands for regular expression and is used for applying validation checks on the data entered in the attribute by making use of regular expressions.

Default Value: field is for specifying default value of the attribute. If we create a new managed object, the attribute will automatically be set to the default value specified in this field.

Let us add two more attributes to the Customer entity: emailid and contactno (for storing a customer’s e-mail address and contact number, respectively). These two attributes will also be of type: String as shown in the next screenshot. Now, save the .xcdatamodel.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here