React Native Day 11 Scroll View

We will try to acheive below out put using scrollview :).

 

Scroll View is a content view that can contain a number of subviews and user can scroll up down.

We can use ScrollView component for this purpose. And the other child component will be child/subviews/subcomponent of scrollView.

Lets’ start creating new project:

On terminal/command line type it:

Open App.js with “Atom” or “VSCode” and replace App.js code as per below:

Thanks!!

IoT-1-Making LED light Switch ON and OFF Using “AT-09 BLE Module”, Arduino Uno & iPhone SE

I provide live iOS app training using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what’sapp : +91–7838552946

Hello every one :). Hope you are doing good. We will discuss about communication over BLE between iPhoneSE and Arduino. We will control LED switch ON and OFF from iPhone over bluetooth.

Attached is the video of final output:

Prerequisite

You should first read Bluetooth & Bluetooth fundamentalsdiscovering peripheralsconnecting peripherals for building strong fundamentals on BLE.

Software

  • Download and install latest Arduino IDE from here. At the time of writing this blog it’s version is 1.8.5.
  • You must have latest version of XCode. At the time of writing this blog it is 9.3.1

Hardware

  • I ordered AT-09 ble module (v4.0) from amazon.

    • iPhoneSE with iOS v11.3.
    • I ordered Arduino Uno kit from RoboIndia. Some other Arduino uno hardware which CAN work are:

and

Please support me by comment, like and share my face book page.

Steps

After successful installation of Arduino IDE launch it.

In editor window copy paste below code:

Let’s see what this code is doing:

The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup() function will only run once, after each powerup or reset of the Arduino board.

The serial.begin()function sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. The rate specifies how fast data is sent over a serial line.

The pinMode(pinNumber, OUTPUT)function can be used to decide at what pin number you want the output.

After creating a setup() function, which initializes and sets the initial values, theloop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.

Get the number of bytes (characters) available for reading, that’s what Serial.available() for.  This function check if there is some data available:

serial.read() function reads data received (“a” or “d”) from iPhone device in our case.

We use switch case to determine if data is “a” or  “d”.

digitalWrite(pinNumber, HIGH/LOW)function make our LED light ON or OFF on pin number 13.

All Set! Let’s upload code on Arduino Hardware.

Connect mac and Arduino with USB.

Make sure you have choose “Board:Arduino/Genuino Uno” and port “usbmodem1421Arduino/Genuino Uno”. Over all set up should look like this:

After uploading the code it’s time to setup circuit.

So the connections are as below:

Setting up BLE module

Connect RXD of A-9 BLE module -> TX of Arduino board.

Connect TXD of A-9 BLE module -> RX of Arduino board.

Connect VCC of A-9 BLE module -> 5V of Arduino board.

Connect GND of A-9 BLE module -> GND of Arduino board.

Setting up LED

Connect small leg of RED LED -> GND of Arduino board.

Connect big leg of RED LED -> Pin 13 of Arduino board.

Have a look at below circuit diagram:

Circuit Diagram

Yeah we have successfully set up our circuit. We are almost done setup for Arduino software and  and hardware.

Please support me by comment, like and share my face book page.

We are done half part till now. Let’s understand basic concept from iOS point of view and write some code.

Connection between BLE devices

I have used XCode v9.3.1, swift v4.3.1, iPhone iOS v11.3.1. If you are from non iOS background, then it might be difficult to understand code, but approach and logic is easy to understand. Some technical points:

Central : Our iOS device is central. It discovers services (which includes characteristics).

Peripheral : AT-09 BLE module is peripheral. We will use characteristics “FFE1” to write data “ON” and “OFF”.

CoreBluetooth Framework : In iOS this framework provides required classes and delegate methods to handle events like:

Discovering peripherals

Connecting peripherals

Discovering services

Discovering characteristics etc.

See below diagram how does BLE device connects to each other:

  • Bluetooth Central: This is the node that is trying to connect to a data source. Think of this as the client.
  • Bluetooth Peripheral: This is the node that is providing the primary data source. Think of this as the server.
  • Characteristic: A characteristic can be considered a variable. Characteristics are defined attribute types that contain a single logical value.
  • Service: A group of characteristics live under a “Service”. Services are collections of characteristics and relationships to other services that encapsulate the behavior of part of a device. Service are collection of data and associated behaviors describing a specific function or feature of a peripheral. For example, a heart rate sensor has a Heart Rate service. A peripheral can have more than one service.
  • Descriptors are defined attributes that describe a characteristic value.
  • Each service and characteristic is represented by a UUID which can be either a 16-bit or a 128-bit value.
  • Central’ Job
    • Scanning for peripherals
    • Connecting to a peripheral
    • Disconnecting from a peripheral
    • Discovering services
    • Discovering characteristics of a service
    • Subscribing to a characteristic
    • Receiving data from a characteristic
  • Peripheral’s Job
    • Advertising a service and characteristic
    • Adding service and characteristic to the PeripheralManager
    • Detecting of new subscribers to a characteristics
    • Detecting of unsubscribing
    • Handling of unready state of the device.

Note : Peripheral does not connect to peripheral. and central does not connect to central.

Framework

Core Bluetooth :

Overview

The Core Bluetooth framework provides the classes needed for your apps to communicate with devices that are equipped with Bluetooth low energy wireless technology.

Do not subclass any of the classes of the Core Bluetooth framework. Overriding these classes is unsupported and results in undefined behavior.

class CBCentral

The CBCentral class represents remote central devices that have connected to an app implementing the peripheral role on a local device. That is, when you are implementing the peripheral role using the CBPeripheralManager class, centrals that connect to your local peripheral are represented as CBCentral objects. Remote centrals are identified by universally unique identifiers (UUIDs), represented by NSUUID objects.

scan for other peripherals

Central devices scan for any advertising peripherals and displays it to the user

A central typically uses the information served up by peripherals to accomplish some particular task.

  • A central is kinda like the “boss”. It wants information from a bunch of its workers in order to accomplish a particular task.

It defines logic behind the Core bluetooth communication. It is able to scan, connect and disconnect peripherals and it also consumes information available at each peripheral. The central devices are usually mobile devices or tablets.

class CBPeripheral

The CBPeripheral class represents remote peripheral devices that your app—by means of a central manager (an instance of CBCentralManager)—has discovered advertising or is currently connected to. Peripherals are identified by universally unique identifiers (UUIDs), represented by NSUUID objects. Peripherals may contain one or more services or provide useful information about their connected signal strength.

advertise information as peripheral

  • A peripheral is kinda like the “worker”. It gathers and publishes data to that is consumed by other devices/means central.

The device that has information to share eg. Heart rate or temperature etc. The information can be pushed or advertise over the air.The peripheral devices are things like Heart rate monitor, BLE enables proximity tags, etc.

The following image defines the relationship between central and peripherals:

In the above scenario iOS devices (Central) communicate with the Heart rate Monitoring system (Peripheral) to get heart rate information and shows it on a device.

How Centrals Communicate with Peripherals?

Advertising is the primary way that peripherals make their presence known via Bluetooth LE.

In addition to advertising their existence, advertising packets can contain some data, such as the peripheral’s name. It can also include some extra data related to what the peripheral collects. For example, in the case of a heart rate monitor, the packet also provides heartbeats per minute (BPM) data.

The job of a central is to scan for these advertising packets, identify any peripherals it finds relevant, and connect to individual devices for more information.

class CBService

CBService and its subclass CBMutableService represent a peripheral’s service—a collection of data and associated behaviors for accomplishing a function or feature of a device (or portions of that device). CBService objects in particular represent services of a remote peripheral device (represented by a CBPeripheral object). Services are either primary or secondary and may contain a number of characteristics or included services (references to other services).

A CBPeripheral holds services (each defined as a CBService), and each CBService holds CBCharacteristics.

The following diagram shows the hierarchy of the CBPeripheral:

Let’s code now:

Below is the user interface part:

I will discuss some critical code only here which is very important to understand:

In Below code snippet we are initializing CBCentralManager and telling that CBCentralManager object’s(which is manager)  delegate is self (means we will implement delegate methods in ViewController class). The discover peripheral method is called when we click on “Discover Devices Button”

After successfully discover below delegate method didDiscoverPeripheral will be called:

We check if peripheral name is “MLT-05”, We show this information on user interface: 

Next, we hold reference of discovered peripheral in global variable and this time set peripheral’s delegate to self:

And after discovering peripheral we stop scanning.

Overall above code looks like this:

Yeah successfully discovered 🙂 🙂 🙂

Let’s connect now:

The below method will be called when user clicks on Connect button.

The code:

will call

Let’s see it’s implementation:

isMyPeripheralConected – this is the global variable we are holding reference to.

We are setting instance of view controller (self) as delegate of peripheral.

and then let’s discover characteristics after discovered services:

peripheral.discoverCharacteristics will call delegate methoddidDiscoverCharacteristicsFor:

In above code we are holding discover characteristic “FFE1” in global variable myCharacteristic. At this stage we can write  “a” and “d” for “ON” and “OFF” respectively.

Above methods are called when we click on ON and OFF buttons on iOS app.

The below method is responsible to send “a” (click on ON) and “d” (click on OFF) as bytes to our Arduino.

Putting all code together looks like :

Done!

Mistakes/Challenges I faced:

  • I ordered HC-05 module from Amazon which iPhone does not support.
  • While uploading code to Arduino hardware make sure there is no connection to LED and BLE Module. Upload Arduino code first then setup your circuit.
  • Finding peripheral characteristic value (FFE1) to write value (“a” for “ON” & “d” for “OFF”).

Happy coding, hope you enjoyed it :).

Please support me by comment, like and share my face book page.

I provide live iOS app training using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what’sapp : +91–7838552946

Swift – Core Data – Part 1 | Relationships | Delete Rules

I provide live iOS app training using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what’sapp : +91–7838552946

What is core data?

  1. Core Data is a object graph management and persistence Framework”. Core Data is a framework that you use to manage the model layer objects in your application.It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.”
  2. Core Data is a model layer technology. Core Data helps you build the model layer that represents the state of your app. Core Data is also a persistent technology, in that it can persist the state of the model objects to disk.”
  3. It’s focus is on objects rather than the traditional table-driven relational database approach. When storing data, you are actually storing an object’s contents, where an object is represented by an Objective-C/Swift class that inherits the NSManagedObject class. A typical application will have several objects used together, forming an object graph.”
  4. Most imp point A Core Data consist of following stack objects:

    • a managed object model
    • a managed object context
    • a persistent store coordinator
    • a persistent store (storage)

Core Data Stack

A Core Data stack consist of following objects:

  • a managed object model
  • a managed object context
  • a persistent store coordinator
  • a persistent store (storage)

Managed Object Model

  • An object that is an instance of NSManagedObjectModel. An NSManagedObjectModelobject describes a schema, a collection of entities (data models) that you use in your application. It uses a private internal store to maintain its properties and implements all the basic behavior required of a managed object.

For Example in the attached screen shot Organization is managed object model and it contains internal properties/attributes like id and name.

 

  • The managed object model represents the data model of the application. 
  • An object that describes a schema—a collection of entities (data models) that you use in your application.
  • Even though Core Data isn’t a database, you can compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.
  • The managed object model is an instance of NSManagedObjectModel and describes the schema used in your Core Data application. It is loaded from the model file which contains all the entity descriptions with their attributes and relationships that you defined in the Core Data Model inspector. So the model describes your objects.

Managed Object Context

A managed object should always be associated with a managed object context. There are no exceptions to this rule. Remember that a managed object context manages a number of records or managed objects. Managed Object Context is instance of class “ManagedObjectContext”.

 

Persistent Store Coordinator

The persistent store coordinator is the glue of the Core Data stack. It keeps a reference to the managed object model and the managed object context. And, as the name implies, the persistent store coordinator is in charge of the persistent store of the application.

A coordinator that associates persistent stores with a model (or a configuration of a model) and that mediates between the persistent stores and the managed object contexts.

Persistent Store Coordinator are actually the instances of “NSPersistentStoreCoordinator” class.

Persistent store

A persistent store is a repository in which managed objects may be stored. You can think of a persistent store as a database data file where individual records each hold the last-saved values of a managed object. Core Data offers three native file types for a persistent store: binary, XML, and SQLite. From the above screen shot you can see persistent store coordinates with Persistent store coordinator.

Object Graph

In computer science, in an object-oriented program, groups of objects form a network through their relationships with each other—either through a direct reference to another object or through a chain of intermediate references. These groups of objects are referred to as object graphs.

An object graph is a view of an object system at a particular point in time. 

Object-oriented applications contain complex webs of interrelated objects. Objects are linked to each other by one object either owning or containing another object or holding a reference to another object to which it sends messages. This web of objects is called an object graph.

Examples:

An array object that contains a single string object represents a small, simple object graph.

A group of objects containing an application object, with references to the windows, menus and their views, and other supporting objects, may represent a large, complex object graph.

Data Model

LIBRARY DATA MODEL

The Library entity has two attributes, name and location, both of type String. The Author entity also has two attributes, firstName and lastName, both of type String. The Book entity has three attributes, title of type StringpublicationDate of type Date, and pages of type Integer 16. This is what the data model should look like in the data model graph.

 

RELATIONSHIPS

A relationship specifies the entity, or the parent entity, of the objects at the destination.

TO-ONE RELATIONSHIPS —>

A book belongs to a library. This means that we need to create a relationship that links a book to a library.

Steps :

  1. Open Library.xcdatamodeld and switch to the editor’s table style.
  2. Select the Book entity.
  3. Click the plus button at the bottom of the Relationships table to add a relationship to the entity.
  4. Set Relationship to library and Destination to the Library entity. Leave Inverse empty for now.
  5. Switch to the editor’s graph style to visual representation of the relationship we defined.

We can conclude below points :

  1. The relationship is to-one relationship.
  2. A book can belong to one library only.
  3. The single arrow is pointing from book entity to library entity.
  4. There is no arrow pointing back from Library to Book, so there is no inverse relationship. It means that the library the book belongs to does not know that the library belongs to this book.

How to make a relationship system where library knows what books it contains. We have following relationship :

INVERSE RELATIONSHIPS <—->

Steps :

  1. Switch to editor’s table style and select the Library entity.
  2. Add a relationship named books.
  3. Set Destination to Book and set Inverse to library.

Switch to the data model graph to see what that looks like. The connection between Library and Book contains arrows pointing to and from each entity. See :

TO-MANY RELATIONSHIPS —>>

Ideally a library should have more than one books. Steps :

  1. Select the books relationship of the Library entity in the editor’s table style. Open the Data Model Inspector in the Utilities pane on the right to see the details of the relationship.
  2. In the Data Model Inspector, you can modify the relationship’s destination and inverse relationship. You can also modify the relationship’s type or cardinality. Core Data supports To-One and To-Many relationships. Set Type to To-Many.

Switch back to graph to see changes. The relationship from Library to Book now has two arrows, indicating that books is a to-many relationship.

MANY-TO-MANY RELATIONSHIPS <<—>>

There might be a real word scenario where book/books can belong to many libraries. To fulfill this relationship we need to turn the library relationship into a to-many relationship.

Select the library relationship of the Book entity in the editor’s table style and set Type to To-Many in the Data Model Inspector.

For the best naming convention practices update the name of the relationship to libraries so that it is easily understood that a book can belong to multiple libraries.

This is what the data model graph looks like after the changes. The relationship that links the Library and Book entities is now a many-to-many relationship.

Very important note

The recommended approach is to model relationships in both directions and specify the inverse relationships appropriately. Core Data uses this information to ensure the consistency of the object graph if a change is made.

Reference of apple documentation

You might get this warning if you set no inverse relationship in Xcode:

warning: Misconfigured Property: Person.address should have an inverse

Fix

Just add a inverse relationship from Address to Person and warning is gone.

Add relationship from Address to Person(Destination) like this :

And finally it should look like this :).

Let’s write some code to understand relationships:

Create a new project in Xcode. Choose single view from project template, give it name CoreDataRelationships andand include Core Data. Now click on CoreDataRelationships.xcdatamodeld. We will add some entities and relationships in Editor.

Write now your editor will blank looking like below image:

 

Click on Add Entity button and create entities. For example create two entities Person and Passport as below screen shot :

Click on + icon in attribute section to add some attributes for Person and Passport entity. Create firstName & lastName attributes of Person entity as per below image:

 

Similarly create passportId attribute as per below image:

One to one example

A person can only have one passport.So we will create a relationship from person to passport. Click on + icon under relationships . As soon as you will click on it a relationship will be created. See attached image:

Enter passport string in relationship.

Enter Passport in destination field.

Similarly click on Passport entity. click on + icon to create a relationship.

Enter person string in relationship

Enter Person in destination.

finally click on inverse and choose Person. Finally complete setup will look like this:

 

 

 

Build once to make sure every thing is perfect.

Core data automatically generates helper files for us at location

~/Library/Developer/Xcode/DerivedData

The complete path in my case is :

~/Library/Developer/Xcode/DerivedData/CoreDataRelationships-gmfbavojplsilicxammyddhvvgqy/Build/Intermediates.noindex/CoreDataRelationships.build/Debug-iphonesimulator/CoreDataRelationships.build/DerivedSources

This is the attached screen shot:

Let’s explore it further:

So, you can see number of autogenerated files for. Let’s see some important files:

Passport+CoreDataClass

The class is a model and is subclass of NSManagedObject. It follows naming convention EntityName+CoreDataClass. following naming convention here it is Passport+CoreDataClass.

Passport+CoreDataProperties.swift

See the magic, this extension automatically provides some helper methods for us. Example it provides us fetchRequest, and automatically created properties passportId & person. @NSManaged means we are telling compiler the value to these properties will be computed at runtime.

Similarly we have two more files for Person Person+CoreDataClass.swift & Person+CoreDataProperties.swift. Explanation remains same as above.

Let’s open Main.storyboard drag drop two UILabels, name them lblPassportdetails and lblVehicalDetails (will use in another example), create IBOutlets & make a setup like this:

 

 

Let’s copy and paste below code in ViewController file:

Now call oneToOneExample() from viewDidLoad() method like this:

Build and run your project, we should see out put like this:

One to many example <—>>

Best example for one to many relationship is – a person can have more than one vehicles. Let’s design this system.

Relationship between Person and Vehicals looks like this

 

Open ViewController file copy paste below code:

Complete code of ViewController class should look like this:

Final Output  😀

Source code is here.

DELETE RULES

Delete rules are one of the conveniences that make working with Core Data great. Every relationship has a delete rule. It defines what happens when the record that owns the relationship is deleted. Let me explain what that means.

Core Data supports four delete rules:

Cascade, Deny, Nullify, No Action.

Cascade

Cascade delete with one to one inverse

Delete the objects at the destination of the relationship when you delete the source.

For example, if you delete a department, fire all the employees in that department at the same time.

Lets See an example where we have a Cascade delete rule.

We have two entities “Person” and Address.

Person have the inverse relationship with Address. 

Address have the inverse relationship with Person. 

Delete rule is cascade for Address entity.

Delete rule is cascade for Person entity.

It is a inverse relationship, that is destination entity knows about the state of source. Here “Person” knows about “Address” and vice versa. If we delete person entity, then address should also be delete.

Lets see in the video example what’s going on:

video

Source Code

Cascade delete with one to one no inverse

Lets say there in unidirectional relationship from person to address but not vice versa. It means if we delete person entity, address entity still exist. Because person nows about address but address do not have inverse relationship back to person entity. “Thats why it is encouraged to use bidirectional relationship”

Source Code

Video

Deny

If there is at least one object at the relationship destination (employees), do not delete the source object (department).

For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere; otherwise, the department cannot be deleted.

Nullify

Remove the relationship between the objects, but do not delete either object.

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. This is the default delete rule and the delete rule you will find yourself using most often.

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.

That’s it for now from basic fundamentals. Working on code examples now and will post them very soon.

Next part 🙂 !! Here you go!!

I provide live iOS app training using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what’sapp : +91–7838552946

 

 

Interview Questions And Answers – Core Data

I provide live iOS app training using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what’sapp : +91–7838552946

  1. What is object graph in core data?
  2. What is core data?
  3. What is data persistance?
  4. What is core data stack?
  5. Give a example of data model?
  6. What are relationships in core data?
  7. What is abstract entity in core data?
  8. How to achieve Inheritance in core data entities?
  9. What is mainConcurrencyType?
  10. What is privateConcurrencyType?
  11. What is managed object context?
  12. How to create managed Object Context
  13. How to perform background task in core data
  14. Can we have more than one MOC
  15. Will you ever pass managedObject from one context to another context
  16. How to pass one managedObject from one context to other context
  17. What do you mean by thread safe
  18. What are different ways of creating private context
  19. How to write code for perform some long running task in background in core data
  20. What are core data delete rules
  21. What is NSAsynchronousFetchRequest
  22. How to set up NSAsynchronousFetchRequest
  23. How we can do multithreading with core data?
  24. How to transfer manage object from one thread to another thread?
  25. what is CoreData and what do we use it for
  26. is CoreData == sqlite or some wrapper?
  27. what types of stores does core data support
  28. What is the minimum necessary classes and relationship between them?
  29. Can the NSPersistentStoreCoordinator have more persistent stores?
  30. What is an NSManagedObjectId
  31. What is lazy initialization, how does this relate to core data, situations when this can be handy
  32. How to read only a few attributes of an entity
  33. What is a fetchedresultcontroller
  34. How to synchronize contexts
  35. How could one simulate an NSManagedObject (dynamic properties)
  36. What is relation
  37. what is insert command
  38. what is update command
  39. what is delete command
  40. persistant vs transient
  41. set up core data stack in iOS 9
  42. 5-6 points core data vs sqlite
  43. what is NSFetchResultController, will it block main UI
  44. When to do core data light weight migration all scenarios

Please support us by comment, like and share our facebook page.

Answers:

Object Graph

In computer science, in an object-oriented program, groups of objects form a network through their relationships with each other—either through a direct reference to another object or through a chain of intermediate references. These groups of objects are referred to as object graphs.

An object graph is a view of an object system at a particular point in time. 

Object-oriented applications contain complex webs of interrelated objects. Objects are linked to each other by one object either owning or containing another object or holding a reference to another object to which it sends messages. This web of objects is called an object graph.

Examples:

An array object that contains a single string object represents a small, simple object graph.

A group of objects containing an application object, with references to the windows, menus and their views, and other supporting objects, may represent a large, complex object graph.

Core Data

  1. Core Data is a object graph management and persistence Framework”. Core Data is a framework that you use to manage the model layer objects in your application.It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.”
  2. Core Data is a model layer technology. Core Data helps you build the model layer that represents the state of your app. Core Data is also a persistent technology, in that it can persist the state of the model objects to disk.”
  3. Core Data’s focus is on objects rather than the traditional table-driven relational database approach. When storing data, you are actually storing an object’s contents, where an object is represented by an Objective-C/Swift class that inherits the NSManagedObject class. A typical application will have several objects used together, forming an object graph.”
  4. Most imp point A Core Data consist of following stack objects:

    • a managed object model
    • a managed object context
    • a persistent store coordinator
    • a persistent store (storage)

Persistance Data

Save data in hard disk, so that it is available in multiple launched/ save data permanently.

Core Data Stack

A Core Data stack consist of following objects:

  • a managed object model
  • a managed object context
  • a persistent store coordinator
  • a persistent store (storage)

NSManagedObjectModel

  • An object that is an instance of NSManagedObjectModel. An NSManagedObjectModelobject describes a schema, a collection of entities (data models) that you use in your application. It uses a private internal store to maintain its properties and implements all the basic behavior required of a managed object.
  • The managed object model represents the data model of the application. 
  • An object that describes a schema—a collection of entities (data models) that you use in your application.
  • Even though Core Data isn’t a database, you can compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.
  • The managed object model is an instance of NSManagedObjectModel and describes the schema used in your Core Data application. It is loaded from the model file which contains all the entity descriptions with their attributes and relationships that you defined in the Core Data Model inspector. So the model describes your objects.

Managed Object Context

A managed object should always be associated with a managed object context. There are no exceptions to this rule. Remember that a managed object context manages a number of records or managed objects.

Persistent Store Coordinator

The persistent store coordinator is the glue of the Core Data stack. It keeps a reference to the managed object model and the managed object context. And, as the name implies, the persistent store coordinator is in charge of the persistent store of the application.

A coordinator that associates persistent stores with a model (or a configuration of a model) and that mediates between the persistent stores and the managed object contexts.

Persistent Store Coordinator are actually the instances of “NSPersistentStoreCoordinator” class.

Persistent store

A persistent store is a repository in which managed objects may be stored. You can think of a persistent store as a database data file where individual records each hold the last-saved values of a managed object. Core Data offers three native file types for a persistent store: binary, XML, and SQLite. From the above screen shot you can see persistent store coordinates with Persistent store coordinator.

Data Model

LIBRARY DATA MODEL

The Library entity has two attributes, name and location, both of type String. The Author entity also has two attributes, firstName and lastName, both of type String. The Book entity has three attributes, title of type StringpublicationDate of type Date, and pages of type Integer 16. This is what the data model should look like in the data model graph.

Please support us by comment, like and share our facebook page.

RELATIONSHIPS

A relationship specifies the entity, or the parent entity, of the objects at the destination.

TO-ONE RELATIONSHIPS —>

A book belongs to a library. This means that we need to create a relationship that links a book to a library.

Steps :

  1. Open Library.xcdatamodeld and switch to the editor’s table style.
  2. Select the Book entity.
  3. Click the plus button at the bottom of the Relationships table to add a relationship to the entity.
  4. Set Relationship to library and Destination to the Library entity. Leave Inverse empty for now.
  5. Switch to the editor’s graph style to visual representation of the relationship we defined.

We can conclude below points :

  1. The relationship is to-one relationship.
  2. A book can belong to one library only.
  3. The single arrow is pointing from book entity to library entity.
  4. There is no arrow pointing back from Library to Book, so there is no inverse relationship. It means that the library the book belongs to does not know that the library belongs to this book.

How to make a relationship system where library knows what books it contains. We have following relationship :

INVERSE RELATIONSHIPS <—->

Steps :

  1. Switch to editor’s table style and select the Library entity.
  2. Add a relationship named books.
  3. Set Destination to Book and set Inverse to library.

Switch to the data model graph to see what that looks like. The connection between Library and Book contains arrows pointing to and from each entity. See :

TO-MANY RELATIONSHIPS —>>

Ideally a library should have more than one books. Steps :

  1. Select the books relationship of the Library entity in the editor’s table style. Open the Data Model Inspector in the Utilities pane on the right to see the details of the relationship.
  2. In the Data Model Inspector, you can modify the relationship’s destination and inverse relationship. You can also modify the relationship’s type or cardinality. Core Data supports To-One and To-Many relationships. Set Type to To-Many.

Switch back to graph to see changes. The relationship from Library to Book now has two arrows, indicating that books is a to-many relationship.

MANY-TO-MANY RELATIONSHIPS <<—>>

There might be a real word scenario where book/books can belong to many libraries. To fulfill this relationship we need to turn the library relationship into a to-many relationship.

Select the library relationship of the Book entity in the editor’s table style and set Type to To-Many in the Data Model Inspector.

For the best naming convention practices update the name of the relationship to libraries so that it is easily understood that a book can belong to multiple libraries.

This is what the data model graph looks like after the changes. The relationship that links the Library and Book entities is now a many-to-many relationship.

Very important note

The recommended approach is to model relationships in both directions and specify the inverse relationships appropriately. Core Data uses this information to ensure the consistency of the object graph if a change is made.

Reference of apple documentation

You might get this warning if you set no inverse relationship in Xcode:

warning: Misconfigured Property: Person.address should have an inverse

Fix

Just add a inverse relationship from Address to Person and warning is gone.

Add relationship from Address to Person(Destination) like this :

And finally it should look like this :).

Abstract Entities

Specify that an entity is abstract if you will not create any instances of that entity. You typically make an entity abstract if you have a number of entities that all represent specializations of (inherit from) a common entity that should not itself be instantiated. For example, in the Employee entity you could define Person as an abstract entity and specify that only concrete subentities (Employee and Customer) can be instantiated. By marking an entity as abstract in the Entity pane of the Data Model inspector, you are informing Core Data that it will never be instantiated directly.

An Entity can be abstract, in which case it is never directly attached to a managed object.

An abstract object (in programming) or entity (in Core Data) is an object or entity that is never instantiated.

Entity Inheritance

Entity inheritance works in a similar way to class inheritance; and is useful for the same reasons. If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity. Rather than specifying the same properties in several entities, you can define them in one entity, and the subentities inherit them. For example, you might define a Person entity with attributes firstName and lastName, and subentities Employee and Customer, which inherit those attributes. An example of this layout is shown in Figure 2-3. Display the layout diagram by clicking the Editor Style buttons in the lower-right corner.

In many cases, you also implement a custom class to correspond to the entity from which classes representing the subentities also inherit. Rather than implementing business logic common to all the entities several times over, you implement them in one place and they are inherited by the subclasses.