CoreData and MagicalRecord (1), magicalrecord

Source: Internet
Author: User

[Conversion] CoreData and MagicalRecord (1), magicalrecord

First, let's take a rough look at some core concepts in CoreData.

1. core concepts of CoreData

First, let's look at two key concepts.

(1) NSManagedObjectModel the managed Object Model (MOM) describes the data model of an application. This model includes Entity, Property, and FetchRequest.


This MOM is described by an object, that isNSEntityDescriptionThe collection of instances. For more information about Object Description objects, see section 7th.

Purpose: Add attributes of an object to establish the relationship between attributes.

(2) NSManagedObjectContext: The hosted object context (MOC) participates in the whole process of various operations on the Data Object and detects changes to the data object, supports undo/redo and updates the data-bound UI.

In concept 2, when the managed object context (MOC) acquires an object from the persistent storage (NSPersistentStore) through the persistent Storage Coordinator (PSC, these objects form a temporary copy to form an object set in MOC, which contains objects and some relationships between objects. We can modify these copies and save them. Then, MOC will operate NSPersistentStore through PSC, and the persistent storage will change.

In CoreDataNSManagedObjectModel: data model of the managed object (MOM), Registered through MOC. MOC supports insert, delete, and update data models, and supports undo and redo operations.

Purpose: insert, update, and delete data.

(3) NSPersistentStoreCoordinator persistent Storage Coordinator (PSC) is equivalent to the data file manager, which processes the underlying reading and writing of data files. Generally, we do not need to deal with it.


A collection of framework objects that provide access channels between applications and external data storage objects is collectively referred to as a persistence stack ). At the top of the stack is the hosted object context (MOC), and at the bottom of the stack is the persistent object Storage (persistent object stores ). The persistent Storage Coordinator (PSC) is between the hosted object context and Persistent Object Storage ). Applications access Persistent Object Storage through instances like NSPersistentStoreCoordinator.

The persistent Storage Coordinator provides an access interface for one or more hosted object contexts, so that multiple persistent storage at the lower layer can be represented as a single aggregated storage. A managed object context can create an object graph based on all the data storage under the persistent Storage Coordinator. The persistent Storage Coordinator can only be associated with one managed Object Model (MOM.

(4) NSManagedObject managed object (MO) data object is associated with MOC

Managed Objects must inherit fromNSManagedObjectOrNSManagedObject. NSManagedObject can express any entity. It uses a private internal storage to maintain its properties and implement all the basic actions required to host objects. The managed object has a reference pointing to the object description.NSEntityDescription Entity descriptionDescribes the object metadata, including the Object Name, object attributes, and the relationship between objects.

(5) Controller

Concept 1 the green controllers, including Array Controller, Object Controller, and Tree Controller, usually bind the Managed Object Context to them through control + drag, in this way, we can operate data visually in nib.

(6) NSFetchRequest

When you use a hosted object context to retrieve data, a fetch request is created ). Similar to SQL query statements.

(7) NSEntityDescription Entity description

The object description object provides metadata for an object, including the object Name, class Name, Properties, and Relationships).

(8). xcdatamodeld


It contains the. xcdatamodeld file, which is edited in the data model editor and compiled into a. momd or. mom file.

We can select our application (the path is similar/Users/Childhood/Library/Application Support/iPhone Simulator/7.1/Applications/005D926F-5763-4305-97FE-AE55FE7281A4), Right-click to display the package content. We can see that.

We focus on understanding the cooperative working relationships between them.

 

# Pragma mark-CoreDataAbout-(void) saveContext {NSError * error = nil; NSManagedObjectContext * managedObjectContext = self. managedObjectContext; if (managedObjectContext! = Nil) {if ([managedObjectContext hasChanges] &! [ManagedObjectContext save: & error]) {NSLog (@ "Unresolved error: % @, % @", error, [error userInfo]); abort ();} else {NSLog (@ "save success! ") ;}}- (NSURL *) applicationDocDir {NSURL * url = [[[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] lastObject]; NSLog (@ "% @", [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]); return url;} // suffix is. xcdatamodeld package, which is. xcdatamodel file, edited in the data model editor // compiled. momd or. mom file-(NSManagedObjectModel *) managedObjectModel {If (_ managedObjectModel! = Nil) {return _ managedObjectModel;} NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "Journal" withExtension: @ "momd"]; NSLog (@ "model url: % @ ", [modelURL path]); self. managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; return self. managedObjectModel;}-(NSManagedObjectContext *) managedObjectContext {if (_ managedObjectContext! = Nil) {return _ managedObjectContext;} NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; if (coordinator! = Nil) {self. managedObjectContext = [[NSManagedObjectContext alloc] init]; [self. managedObjectContext setPersistentStoreCoordinator: coordinator];} return self. managedObjectContext;}-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {if (_ persistentStoreCoordinator! = Nil) {return _ persistentStoreCoordinator;} NSURL * storeUrl = [[self applicationDocDir] URLByAppendingPathComponent: @ "Journal. sqlite "]; NSError * error = nil; self. persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]; if (! [Self. persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeUrl options: nil error: & error]) {NSLog (@ "Error: % @, % @", error, [error userInfo]);} return self. persistentStoreCoordinator ;}
  • The application first creates or reads the model file (Suffix: xcdatamodeld) to generate the NSManagedObjectModel object.
  • Generates NSManagedObjectContext and NSPersistentStoreCoordinator objects. MOC sets its own persistent Storage Coordinator (PSC) and calls PSC to read and write data files.
  • NSPersistentStoreCoordinator is responsible for reading data from data files (xml, sqlite, binary files, etc.) to generate a Managed Object, or saving a Managed Object to write data files.
  • NSManagedObjectContext is used to perform various operations on data. It can hold multiple Managed objects. We use it to monitor Managed objects. Monitoring data objects have two functions: undo/redo and data binding. This class is the most commonly used
  • Array Controller, Object Controller, and Tree Controller are generally associated with NSManagedObjectContext. Therefore, we can use them to operate Data Objects visually in nib.

 

2. Model class

The model is a bit like the table structure of the database. It contains Entry, and the entity contains three types of properties: Attribute, RelationShip, and Fetched Property ). Model class names end with "Description. We can see that the model describes the data type and Its Relationship.

The main Model classes are:

 

Model Classes
Managed Object Model NSManagedObjectModel Data Model
Entity NSEntityDescription ABSTRACT Data Type, equivalent to tables in the database
Property NSPropertyDescription The Entity feature is equivalent to a column in the database table.
> Attribute NSAttributeDescription Basic numeric attributes (such as Int16, BOOL, Date, and other attributes)
> Relationship NSRelationshipDescription Relationship between attributes
> Fetched Property NSFetchedPropertyDescription Query attributes (equivalent to query statements in the database)

 

1) Entity-NSEntityDescription
Entity is equivalent to a table in a database. It describes an abstract data type. Its Class is NSManagedObject or its subclass.

Common NSEntityDescription methods:
+ InsertNewObjectForEntityForName: inManagedObjectContext: Factory method. Based on the given Entity description, generate the NSManagedObject object and insert it into ManagedObjectContext.
-ManagedObjectClassName: The NSManagedObject class name mapped to the Entity is returned.
-AttributesByName indicates the key and returns the Attributes in the Entity.
-The relationshipsByName is named as the key and returns the corresponding Relationships in the Entity.

2) Property-NSPropertyDescription
Property is the feature of Entity, which is equivalent to a column in the database table or a key in the value-key pair in the XML file. It can describe the RelationShip between object data (Attribute), Entity, or the query Attribute (Fetched Property ).

> Attribute-NSAttributeDescription
Attribute stores basic data, such as NSString, NSNumber, or NSDate. It can have a default value, or use a regular expression or other conditions to limit its value. An attribute can be optional.
 
> Relationship-NSRelationshipDescription
Relationship describes the Relationship between Entity and Property. It can be one-to-one or one-to-many.

> Fetched Property-NSFetchedPropertyDescription
Fetched Property returns the Qualified Data Object of the specified Entity based on the query predicate.

The above is more abstract. For example, see the figure below:

 

We have a CocoaDataDemo. xcdatamodeld model file. The application generates an NSManagedObjectModel object based on it. This model has three Entity, and each Entity can contain three types of properties: Attribute Relationship and Feteched Property. In this example, Author Entity contains two attributes: name and email. They are for the runtime class NSManagedObject, and contain a Relationship with Post; Feteched Property is not set.

We usually use the KVC mechanism to access the Property. Let's look at the code below:

NSManagedObjectContext * context = [[NSApp delegate] managedObjectContext];NSManagedObject        * author  = nil;    author = [NSEntityDescription insertNewObjectForEntityForName: @"Author" inManagedObjectContext: context];[author setValue: @"nemo@pixar.com" forKey: @"email"];NSLog (@"The Author's email is: %@", [author valueForKey:@"email"]);

 

In the above Code, we first obtain NSManagedObjectContext, then call the NSEntityDescription method, use Author as the entity model, generate the corresponding NSManagedObject object, and insert it into NSManagedObjectContext, then set the feature email value for this object.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.