First, coredata is divided into five modules.
In, we can see that there are five related modules:
1. Managed Object Model
The managed object model is a data model that describes an application. This model contains entities, properties, and fetch requests. (English terms are used below .)
2, managed object context
Managed object context participates in the whole process of various operations on the data object, and monitors the changes of the data object to provide support for Undo/Redo and update the UI bound to the data.
3. Persistent store Coordinator
Persistent store coordinator 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.
4. Managed object
The managed object data object, which is associated with the managed object context.
5, Controller
In the figure, the green controllers include array controller, object controller, and tree controller. These controllers are usually bound to managed object context through control + drag, so that we can operate data visually in nib.
How does this write module work?
1. The application first creates or reads the model file (Suffix: xcdatamodeld) to generate the nsmanagedobjectmodel object. The document application generally reads data from the model file (Suffix: xcdatamodeld) through nsdocument or its subclass nspersistentdocument.
2. Then, the nsmanagedobjectcontext and nspersistentstorecoordinator objects are generated. The former transparently calls the latter to read and write data files.
3. nspersistentstorecoordinator reads data from data files (XML, SQLite, binary files, and so on) to generate a managed object, or save a managed object and write it into the data file.
4. nsmanagedobjectcontext is involved in the entire process of various operations on data. It holds a managed object. 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.
5. arrays controller, object controller, and tree controller are generally associated with nsmanagedobjectcontext. Therefore, we can operate Data Objects visually in nib.
Ii. 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:
[CPP]View plaincopyprint?
- Nsmanagedobjectcontext * context = [[nsapp Delegate] managedobjectcontext];
- Nsmanagedobject * Author = nil;
- Author = [nsentitydescription insertnewobjectforentityforname: @ "author" inmanagedobjectcontext: Context];
- [Author setvalue: @ "[email protected]" 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.
Iii. runtime classes and objects
> Managed object-nsmanagedobject
Managed object indicates a record in the data file, and each managed object corresponds to a data representation of entity in the memory. The managed object member is described by the entity property.
For example, in the above Code, the nsmanagedobject of author corresponds to the entity named author.
Each managed object has a global ID (type: nsmanagedobjectid ). Managed object will be appended to a managed object context. We can use this global ID to query the corresponding managed object in the managed object context.
Common nsmanagedobject Methods
| -Entity |
Obtain its Entity |
| -Objectid |
Obtain the managed Object ID. |
| -Valueforkey: |
Obtains the value of a specified property. |
| -Setvalue: forkey: |
Set the value of the specified property |
> Managed object context-nsmanagedobjectcontext
The role of managed object context is very important. Operations on data objects are related to it. When a data object is created and inserted into the managed object context, the managed object context starts to track all changes to the data object and provides Undo/Redo support when appropriate, or call persistent store coordinato to save the changes to the data file.
We usually bind the Controller class (such as nsarraycontroller and nstreecontroller) or its subclass to the managed object context, so that we can generate and obtain data objects dynamically.
Common nsmanagedobjectcontext Methods
| -Save: |
Save data objects to data files |
| -Objectwithid: |
Queries the Data Object of the specified managed Object ID. |
| -Deleteobject: |
Mark a data object as deleted, but the data object will not be deleted until the context changes are submitted. |
| -Undo |
The last step of rollback is supported by all undo/Redo operations. |
| -Lock |
Locks are often used for multithreading and transaction creation. Similar interfaces include-unlock and-trylock. |
| -Rollback |
Restore Data File Content |
| -Reset |
Clear the cached managed objects. It should be used only when persistent stores is added or deleted. |
| -Undomanager |
Returns the nsundomanager used by the current context. |
| -Assignobject: topersistantstore: |
Because context can manage data objects from different data files, This interface is used to specify the data object storage file (implemented by specifying persistantstore) |
| -Executefetchrequest: Error: |
Execute the fetch request and return all matched data objects. |
> Persistent store coordinator-nspersistentstorecoordinator
Applications of the core data document type usually read or store data from the data files on the disk. The underlying read/write operations are handled by persistent store coordinator. In general, we don't need to deal with it directly to read and write files. The managed object context has done this for us to call persistent store coordinator.
Common nspersistentstorecoordinator Methods
| -Addpersistentstoreforurl: configuration: URL: Options: Error: |
The corresponding interface for unloading data storage is-removepersistentstore: Error: |
| -Migratepersistentstore: tourl: Options: withtype: Error: |
Migrate data storage, the effect is similar to "save as", but after the operation is successful, Data storage before migration is unavailable |
| -Managedobjectidforurirepresentation: |
Returns the ID of the data storage object indicated by the given URL. If no matching data storage is found, Nil is returned. |
| -Persistentstoreforurl: |
Returns the persistent store in the specified path. |
| -Urlforpersistentstore: |
Returns the storage path of the specified persistent store. |
> Persistent document-nspersistentdocument
Nspersistentdocument is a subclass of nsdocument. The multi-document core data application uses it to simplify operations on core data. Generally, the default Implementation of nspersistentdocument is enough. It reads document types information from info. plist to determine the data storage format (XML, SQLite, binary ).
Common nspersistentdocument Methods
| -Managedobjectcontext |
Return the managed object context of the document. In multi-document applications, each document has its own context. |
| -Managedobjectmodel |
Returns the managed object model of the document. |
4. Fetch requests
Fetch requests is equivalent to a query statement. You must specify the entity to be queried. We use fetch requests to query Qualified Data Objects from the managed object context and return the query results in the form of nsarray. If no query conditions are set, all data objects of the entity are returned. We can use predicates to set query conditions. Usually, the commonly used fetch requests are saved to the dictionary for reuse.
Example:
[CPP]View plaincopyprint?
- Nsmanagedobjectcontext * context = [[nsapp Delegate] managedobjectcontext];
- Nsmanagedobjectmodel * model = [[nsapp Delegate] managedobjectmodel];
- Nsdictionary * entities = [model entitiesbyname];
- Nsentitydescription * entity = [entities valueforkey: @ "Post"];
- Nspredicate * predicate;
- Predicate = [nspredicate predicatewithformat: @ "creationdate >%@", date];
- Nssortdescriptor * sort = [[nsortdescriptor alloc] initwithkey: @ "title"];
- Nsarray * sortdescriptors = [nsarray arraywithobject: Sort];
- Nsfetchrequest * fetch = [[nsfetchrequest alloc] init];
- [Fetch setentity: entity];
- [Fetch setpredicate: predicate];
- [Fetch setsortdescriptors: sortdescriptors];
- Nsarray * Results = [context executefetchrequest: Fetch error: Nil];
- [Sort release];
- [Fetch release];
In the above Code, We query the post created after the specified date, and return the query result in order by title.
Common nsfetchrequest Methods
| -Setentity: |
Set the data object type (entity) You want to query) |
| -Setpredicate: |
Set query Conditions |
| -Setfetchlimit: |
Set the maximum number of query objects |
| -Setsortdescriptors: |
Set the sorting method of query results |
| -Setaffectedstores: |
Set the data storage in which queries can be made |
Coredata Summary 1