Iphone-coredata the use of a detailed
First, the concept
1.Core data is the best way to persist storage
2. The final storage type of the data can be: SQLite database, XML, binary, in-memory, or custom data types
In Mac OS X 10.5Leopard and later versions, developers can also create custom storage formats by inheriting the Nspersistentstore class
3. Benefits: The ability to properly manage memory, avoid the hassle of using SQL, efficient
4. Composition:
(1) Nsmanagedobjectcontext (managed data context)
Manipulating the actual content (Operation persistence layer)
Role: Inserting data, querying data, deleting data
(2) Nsmanagedobjectmodel (managed data model)
Database all tables or data structures containing the definition information for each entity
Role: Adding attributes to entities, establishing relationships between attributes
How to: View Editor, or code
(3) Nspersistentstorecoordinator (persistent storage assistant)
A connector equivalent to a database
Role: Set the name, location, storage, and storage time of the data store
(4) Nsmanagedobject (managed data record)
Equivalent to a table record in a database
(5) Nsfetchrequest (Request to get data)
Equivalent to a query statement
(6) Nsentitydescription (solid structure)
Equivalent to table structure
(7) A package with a. Xcdatamodeld suffix
Inside is the. xcdatamodel file, which is edited with the Data Model Editor
Compiled for. MOMD or. Mom Files
5. Dependency relationship
Second, based on the SQLite database, the simple use of Core data
The difference from SQLite: You can only take the entire entity record and then decompose it before you can get an attribute of the entity
1. Build process
Includes: Creating a data context, creating a data model, creating a data persistence storage assistant
(1) If you create a new project, select the blank application, next
Tick the Use Core data option
In the resulting project file appdelegate, the associated code such as the managed data context is automatically generated
(2) For example, the AppDelegate.h file automatically generates
@property (ReadOnly, Strong, nonatomic) Nsmanagedobjectcontext *managedobjectcontext; @property (ReadOnly, Strong, nonatomic) Nsmanagedobjectmodel *managedobjectmodel; @property (ReadOnly, Strong, Nonatomic) Nspersistentstorecoordinator *persistentstorecoordinator;-(void) savecontext;-(Nsurl *) Applicationdocumentsdirectory;
Method Savecontext: Save data to Persistence layer (database)
Method Applicationdocumentsdirectory means: The documents directory path under the application sandbox
(e.g./var/mobile/applications/5fg80a45-dfb5-4087-a1b1-41342a977e21/documents/)
(3) For example, the AppDelegate.h file automatically generates
@synthesize managedobjectcontext = __managedobjectcontext; @synthesize Managedobjectmodel = __managedobjectmodel;@ Synthesize persistentstorecoordinator = __persistentstorecoordinator;
Saving data to the persistence layer
-(void) Applicationwillterminate: (uiapplication *) application{ [self savecontext];}
-(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 ();}}}
Documents directory path
-(Nsurl *) applicationdocumentsdirectory{ return [[[Nsfilemanager Defaultmanager] Urlsfordirectory: NSDocumentDirectory Indomains:nsuserdomainmask] lastobject];}
Managed data context
After initialization, the persistence storage assistant must be set
-(Nsmanagedobjectcontext *) managedobjectcontext{ if (__managedobjectcontext! = nil) { return __ Managedobjectcontext; } Nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator]; if (Coordinator! = nil) { __managedobjectcontext = [[Nsmanagedobjectcontext alloc] init]; [__managedobjectcontext setpersistentstorecoordinator:coordinator]; } return __managedobjectcontext;}
Managed data Model
The initialization must depend on the. momd file path, and the. momd file is compiled by the. Xcdatamodeld file
-(Nsmanagedobjectmodel *) managedobjectmodel{ if (__managedobjectmodel! = nil) { return __managedobjectmodel ; } Nsurl *modelurl = [[NSBundle mainbundle] urlforresource:@ "TestApp" withextension:@ "MOMD"]; __managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; return __managedobjectmodel;}
Persistent Storage Assistant
Initialization must depend on Nsmanagedobjectmodel, after which you specify the data type of the persisted store, the default is Nssqlitestoretype, the SQLite database, and specify the storage path to the documents directory, and the database name
-(Nspersistentstorecoordinator *) persistentstorecoordinator{ if (__persistentstorecoordinator! = nil) { return __persistentstorecoordinator; } Nsurl *storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@ "Testapp.sqlite"];
Nserror *error = nil; __persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:[self Managedobjectmodel]];
if (![ __persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options: Nil Error:&error]) { NSLog (@ "unresolved error%@,%@", error, [error userInfo]); Abort (); } return __persistentstorecoordinator;}
If it's not a new project, you can also write the relevant code yourself
(4) also generated the Testapp.xcdatamodeld file
(5) also automatically linked to the Coredata.framework
(6) in the precompiled header. pch file, add the CoreData.h header file to the import
#import <CoreData/CoreData.h>
2. Create a data model (Data Model Editor action)
(1) Create an entity
Select the. Xcodedatamodel Object
Click Add entity on the bottom toolbar of the Data Model Editor on the right
Name an entity in the rightmost column
(2) Creating entity properties
Select the entity and click Add Attribute at the bottom of the toolbar for adding properties
Select the newly added property, name the property, and set the data type of the property attribute type
(3) Establishing a relationship for two entities
Select an entity and click Add Relationship in the bottom toolbar
Select a new relationship, add a name to the relationship, and set the target destination to another entity
(4) Establishing a return relationship
(When you build a goal relationship, it's best to build a return relationship)
Establish a relationship in another entity and name it, set the target object to the previous entity
and the relationship name before the inverse attribute is selected
(5) Set delete rule for two relationships delete rules, all associated patterns
Correlation mode cascade: One of the data is deleted and the data in the other entity is deleted
(6) The graph of the final two objects is
Toggle Editor Stype button
You'll see another way to edit it:
3. Inserting data
In APPDELEGATE.M's application:didfinishlaunchingwithoptions: method, call the custom method
Insertcoredata Insert the data with the following code:
-(void) insertcoredata{nsmanagedobjectcontext *context = [self managedobjectcontext]; Nsmanagedobject *contactinfo = [nsentitydescription insertnewobjectforentityforname:@ "ContactInfo" Inmanagedobjectcontext:context]; [ContactInfo setvalue:@ "name B" forkey:@ "name"]; [ContactInfo setvalue:@ "Birthday B" forkey:@ "Birthday"]; [ContactInfo setvalue:@ "Age B" forkey:@ "age"]; Nsmanagedobject *contactdetailinfo = [nsentitydescription insertnewobjectforentityforname:@ "ContactDetailInfo" Inmanagedobjectcontext:context]; [Contactdetailinfo setvalue:@ "Address B" forkey:@ "address"]; [Contactdetailinfo setvalue:@ "name B" forkey:@ "name"]; [Contactdetailinfo setvalue:@ "Telephone B" forkey:@ "Telephone"]; [Contactdetailinfo setvalue:contactinfo forkey:@ "info"]; [ContactInfo setvalue:contactdetailinfo forkey:@ "Details"]; Nserror *error; if (![ Context Save:&error]) {NSLog (@ "cannot be saved:%@", [Error localizeddescription]); }}
Create a data context, call the Insertnewobjectforname method, create two data record Nsmanagedobject, and then assign values to the properties defined in the previous Data Model edit view. At this point the data is modified only in memory, and finally the Save method of the data context is called and saved to the persistence layer
4. Querying data
After you call Insertcoredata, you can call a custom query method datafetchrequest to query the inserted data
-(void) datafetchrequest{ nsmanagedobjectcontext *context = [self managedobjectcontext]; Nsfetchrequest *fetchrequest = [[[[Nsfetchrequest alloc] init] autorelease]; Nsentitydescription *entity = [nsentitydescription entityforname:@ "ContactInfo" inmanagedobjectcontext:context]; [Fetchrequest setentity:entity]; Nserror *error; Nsarray *fetchedobjects = [Context executefetchrequest:fetchrequest error:&error]; For (Nsmanagedobject *info in fetchedobjects) { NSLog (@ "name:%@", [info valueforkey:@ "name"]); NSLog (@ "age:%@", [Info valueforkey:@ "age"]); NSLog (@ "birthday:%@", [info valueforkey:@ "Birthday"]); Nsmanagedobject *details = [info valueforkey:@ "Details"]; NSLog (@ "address:%@", [Details valueforkey:@ "address"]); NSLog (@ "telephone:%@", [details valueforkey:@ "telephone"]);} }
Fetchrequest equivalent to the wrapper class for SQL query statements, you need to use the Setentity method to specify the entity structure of the specific query (table structure)
Returns a pointer to the concrete entity structure through the Entityforname method of the Nsentitydescription
The Executefetchrequest:error: method is then called to perform the query operation, and if the operation succeeds, the corresponding data record array is returned
Where you can query properties in another data record object by Nsmanagedobject the associated property in the data record object
5. Data templates
Generate a Nsmanagedobject subclass for each entity
The Key-value method is used when setting the data and getting the data, and a better way is to access and get the data through the class's member properties by generating a subclass of the strongly typed nsmanagedobject
(1) Select the entity object in the Data editor view,
Choose the File menu, click New, click File ..., select the core data item, select Nsmanagedobject Subclass, generate the class with the same name as the entity,
Inherit from Nsmanagedobject
Generate the corresponding ContactInfo.h file
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class contactdetailinfo; @interface Contactinfo:nsmanagedobject@property (nonatomic, retain) NSString * age; @property (nonatomic, retain) NSString * Birthda y; @property (nonatomic, retain) nsstring * name; @property (nonatomic, retain) contactdetailinfo *details; @end
and CONTACTINFO.M file
Wherein, @dynamic tells the compiler not to do the processing, let the compilation pass, its getter and setter method will be dynamically created at run time, by the core data framework for such properties generated access method
#import "ContactInfo.h" #import "ContactDetailInfo.h" @implementation contactinfo@dynamic age; @dynamic birthday;@ dynamic name; @dynamic details; @end
and ContactDetailInfo.h file
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class contactinfo; @interface Contactdetailinfo:nsmanagedobject@property (nonatomic, retain) NSString * address; @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) NSString * telephone; @property (nonatomic, retain) ContactInfo *info; @end
and CONTACTDETAILINFO.M file
#import "ContactDetailInfo.h" #import "ContactInfo.h" @implementation contactdetailinfo@dynamic address; @dynamic Name , @dynamic telephone; @dynamic info; @end
At this point, in the rightmost column of the Data Model Editor view, the entity's class becomes the specific class name
Before using the Key-value code can be modified to:
#import "ContactInfo.h" #import "ContactDetailInfo.h"
-(void) insertcoredata{ nsmanagedobjectcontext *context = [self managedobjectcontext]; ContactInfo *contactinfo = [nsentitydescription insertnewobjectforentityforname:@ "ContactInfo" Inmanagedobjectcontext:context]; Contactinfo.name = @ "name B"; Contactinfo.birthday = @ "Birthday B"; Contactinfo.age = @ "Age B"; Contactdetailinfo *contactdetailinfo = [nsentitydescription insertnewobjectforentityforname:@ "ContactDetailInfo" Inmanagedobjectcontext:context]; Contactdetailinfo.address = @ "Address B"; Contactdetailinfo.name = @ "name B"; Contactdetailinfo.telephone = @ "Telephone B"; Contactdetailinfo.info = ContactInfo; Contactinfo.details = Contactdetailinfo; Nserror *error; if (![ Context Save:&error]) { NSLog (@ "cannot be saved:%@", [Error localizeddescription]);} }
-(void) datafetchrequest{ nsmanagedobjectcontext *context = [self managedobjectcontext]; Nsfetchrequest *fetchrequest = [[[[Nsfetchrequest alloc] init] autorelease]; Nsentitydescription *entity = [nsentitydescription entityforname:@ "ContactInfo" inmanagedobjectcontext:context]; [Fetchrequest setentity:entity]; Nserror *error; Nsarray *fetchedobjects = [Context executefetchrequest:fetchrequest error:&error]; For (ContactInfo *info in fetchedobjects) { NSLog (@ "name:%@", info.name); NSLog (@ "age:%@", info.age); NSLog (@ "birthday:%@", info.birthday); Contactdetailinfo *details = info.details; NSLog (@ "address:%@", details.address); NSLog (@ "telephone:%@", Details.telephone); }}
Third, database-related
1. Print the hidden SQL statement:
Select Run in the edit scheme, then enter the arguments tag and add the parameter: "-com.apple.coredata.sqldebug 1"
2. When using SQLite storage, the database structure
Stored SQLite database table name: Uppercase "Z" plus entity name uppercase, one entity equivalent to one table
Specific field name: Uppercase "Z" plus entity attribute name uppercase
IOS: Reprint CoreData Database Framework