Core data in-depth parsing

Source: Internet
Author: User

Roche (http://Blog.csdn.net/kesalin)CC License, reprint please specify the source core data is Cocoa processing data, binding Data key features, its importance is self-evident, but also more complex. Core Data has many analogies, and beginners are often less likely to understand them. There are three tutorials to explain this part: Framework explained: The core data framework, the process of operation, the design of the class; Core Data application Example: By building an application that uses Core data to explain how to use the XCode4use Core data in the Create a core Data sample manually: Do not use the framework to generate code automatically, fully write all of the core data related code of the command-line application to drill down to the use of core data. This article is the first part: The framework of a detailed one, an overview of the following first to give a class diagram, let us have a general understanding of it. In, we can see that there are five related modules:1, the Managed object Modelmanaged object model is a data model that describes the application, which contains entities (entity), attributes, read requests (Fetch request), and so on. (English terminology is used below.) )2, Managed object Contextmanaged Object Context participates in the entire process of manipulating data objects and monitors changes in data objects to provide an undo/Redo supports and updates the UI that binds to the data. 3, the persistent store Coordinatorpersistent store coordinator is equivalent to the data File Manager, handling the underlying read and write to the data file. Generally we don't have to deal with it. 4a Managed objectmanaged object that is associated with the Managed object Context. 5, the green Array controller in the controller diagram, the Object controller, the Tree controllers, are generally control+Drag binds the Managed Object Context to them so that we can manipulate the data visually in the 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 is generally read by nsdocument or its subclasses nspersistentdocument) from the model file (suffix Xcdatamodeld). 2, and then generates Nsmanagedobjectcontext and Nspersistentstorecoordinator objects, which transparently call the user to read and write to the data file. 3, Nspersistentstorecoordinator is responsible for reading data from data files (XML, SQLite, binary files, etc.) to generate Managed object, or to save Managed object to write to the data file. 4, Nsmanagedobjectcontext participates in the entire process of doing various operations on the data, and it holds Managed Object. We use it to monitor Managed Object. Monitoring data Objects has two functions: support undo/Redo and data binding. This class is most commonly used. 5, Array Controller, Object Controller, Tree controllers these are typically associated with nsmanagedobjectcontext, so we can manipulate the data objects visually in the nib. Two, Modelclassthe model is somewhat like the database's table structure, which contains Entry, the entity also contains three kinds of property:attribute (attributes), relationship (relationship), fetched property (read attribute). ModelclassThe names of many"Description"end. We can see that the model is the description of the data type and its relationship. The main ModelclassThere are: Model Classes Managed Object model Nsmanagedobjectmodel Data Model entity nsentitydescription abstract data type, equivalent to data The table property in the library nspropertydescription the Entity attribute, which is equivalent to a column in a database table>Attribute nsattributedescription Basic numeric properties (such as Int16, BOOL, date, and other types of properties)>relationship The relationship between Nsrelationshipdescription properties>fetched Property nsfetchedpropertydescription query properties (equivalent to query statements in the database)1) Entity-nsentitydescriptionentity is equivalent to a table in a database that describes an abstract data type whose corresponding class is nsmanagedobject or its subclasses. Nsentitydescription Common methods:+Insertnewobjectforentityforname:inmanagedobjectcontext: The Factory method, based on the given Entity description, generates the corresponding Nsmanagedobject object and inserts The Managedobjectcontext. -Managedobjectclassname returns the Nsmanagedobject class name mapped to Entity-Attributesbyname returns the corresponding Attributes in the Entity with the name Key .-Relationshipsbyname returns the corresponding relationships in the Entity with the name Key .2) Property-Nspropertydescriptionproperty is an attribute of Entity, which is equivalent to a column in a database table, or value in an XML file-Key in the key pair. It can describe the Entity data (Attribute), the relationship between entities (relationship), or query properties (fetched property). > Attribute-Nsattributedescriptionattribute stores basic data, such as NSString, NSNumber or NSDate. It can have a default value, or its value can be qualified with a regular expression or other criteria.  A property can be optional. > Relationship-nsrelationshipdescription Relationship describes the relationship between Entity,property, either one-to-many, or one-to-multiple relationships. > Fetched Property-nsfetchedpropertydescriptionfetched property returns the qualifying data object for the specified Entity, based on the query predicate. The above is more abstract, for example, see figure: We have a Cocoadatademo.xcdatamodeld model file, the application generates a Nsmanagedobjectmodel object based on it, the model has three Entity, each Entity can also contain Attribute relationship, feteched property of three kinds. In this example, the Author Entity contains two attribute:name and e-mails for which the runtime class is Nsmanagedobject, and a relationship with the Post; feteched Pro is not set Perty. We usually use the KVC mechanism to access the property. Here's the code: [CPP] View Plaincopyprint?Nsmanagedobjectcontext* context = [[NsappDelegate] 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 get the Nsmanagedobjectcontext, then call the Nsentitydescription method to Author as the entity model, generate the corresponding Nsmanagedobject object, insert Nsmanagedobjectcontext, then set the value of the attribute email to this object. Third, run-time classes and objects> Managed Object-The Nsmanagedobjectmanaged object represents a record in the data file, and each Managed object corresponds to a data representation of the Entity in memory. The members of the Managed Object are described by the property of the Entity. For example, in the above code, author this nsmanagedobject, corresponding to the Entity named author. Each Managed Object has a global ID (type: Nsmanagedobjectid). The Managed object is appended to a Managed object context, and we can query the corresponding Managed object through this global ID in the Managed object context. Nsmanagedobject Common Methods-entity acquires its entity-ObjectID gets its Managed Object ID-Valueforkey: Gets the value of the specified property-Setvalue:forkey: Sets the value of the specified property> Managed Object Context-The role of nsmanagedobjectcontextmanaged object Context is important, and the operation of the data object is related to it. When a data object is created and inserted into the Managed object context, Managed object context starts to track all changes to this data object and provides the correct time for the undo/redo support, or call persistent store Coordinato to save the changes to the data file. Usually we bind the Controller class (for example: Nsarraycontroller,nstreecontroller) or its subclasses to the Managed object Context, which makes it easy for us to generate dynamically, get data objects, and so on. Nsmanagedobjectcontext Common Methods-Save : Saving Data Objects to a data file-Objectwithid: Querying a Data object that specifies the Managed object ID-DeleteObject: Marks a data object for deletion, but does not actually delete the data object until the Context commits the change-undo rollback The last step, which is all undo/Redo's support-LockLock, often used for multithreading and creating transactions. Similar interfaces include:-unlock and-Trylock-rollback restoring data file contents-Reset clears the cached Managed Objects. Should only be used when adding or removing persistent Stores-UndoManager Returns the Nsundomanager used by the current Context-Assignobject:topersistantstore: Because the Context can manage data objects from different data files, the purpose of this interface is to specify the data object's storage data file (implemented by specifying Persistantstore) 
    -Executefetchrequest:error: Executes the Fetch Request and returns all matching data Objects> Persistent Store Coordinator-Nspersistentstorecoordinator applications that use the Core data document type typically read or store data from the text on disk, which is written at the bottom of the persistent Store Coordinator to deal with. In general, we do not need to deal directly with it to read and write files, Managed Object Context in the back has been for us to call persistent Store Coordinator do this part of the work. Nspersistentstorecoordinator Common Methods-addpersistentstoreforurl:configuration:url:options:error: Load data storage, the corresponding unloading data storage interface is-Removepersistentstore:error:-migratepersistentstore:tourl:options:withtype:error: Migrating data storage, effects and"Save as"similar, but after a successful operation, the data store before migration is no longer available-managedobjectidforurirepresentation: Returns the data store indicated by the given URL.Object IDreturns nil if no matching data store is found-Persistentstoreforurl: Returns the persistent Store for the specified path-Urlforpersistentstore: Returns the storage path for the specified persistent store> Persistent Document-Nspersistentdocumentnspersistentdocument is a subclass of Nsdocument. Multi-The document core data application uses it to simplify the operation of core data. It is often sufficient to use the default implementation of Nspersistentdocument, which reads the Document types information from the Info.plist to determine the storage format (xml,sqlite, binary) of the data. Nspersistentdocument Common Methods-Managedobjectcontext Returns the Managed Object context for the document, where each document has its own context in a multi-document application. -Managedobjectmodel Returns the Managed Object model four of the document, and the Fetch Requestsfetch requests corresponds to a query statement, you must specify the Entity to query. We use Fetch requests to query the Managed object Context for qualifying data Objects, return the query results in nsarray form, and return all data objects for that Entity if we have not set any query criteria. We can use predicates to set query criteria, often saving common Fetch requests to dictionary for reuse. Example: [CPP] View Plaincopyprint?Nsmanagedobjectcontext* context = [[NsappDelegate] Managedobjectcontext]; Nsmanagedobjectmodel* model = [[NsappDelegate] 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 results in the order of title. Nsfetchrequest Common Methods-setentity: Set the type of data object you want to query (Entity)-setpredicate: Setting query Criteria-Setfetchlimit: Set maximum number of query objects-setsortdescriptors: Setting the sorting method for query results-setaffectedstores: Set which data stores you can query for resources: Core data Reference API listing forThe Core Data classeshttp://developer.apple.com/documentation/cocoa/reference/coredata_objc/index.htmlnspredicate Reference API listing fornspredicatehttp://developer.apple.com/documentation/cocoa/reference/foundation/objc_classic/classes/nspredicate.html

Core data in-depth parsing

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.