iOS storage (2) using CoreData

Source: Internet
Author: User
Tags sqlite database

Referring to the database has to mention Orm,orm is to associate the stored data table with the object, manipulate the data in the database by manipulating the relationship between the object and the object, the most commonly used ORM framework in Java is Hibernate,mybatis, these are the third party open source framework, In iOS, Apple has a direct coredata

Important Concepts in CoreData

1:persistentstore

This is where data is stored, iOS offers a variety of persistentstore for developers to choose from, in addition to the Sqlite3 database, as well as binaries, XML files and memory, developers mainly use the first and the next three uses less

2:nsmanagedobjectmodel

The data model, equivalent to all the tables in the database, iOS provides a Xcdatamodeld file to build a data model, a data model can contain multiple entities, entities have their own properties, relationships can exist between entities, Xcdatamodeld compiled as a. momd file

The common initialization methods are as follows

-(Nsmanagedobjectmodel *) managedobjectmodel{ if  (_managedobjectmodel!= nil) { return  
   
     _managedobjectmodel;  
    // 
     Nsurl *modelurl = [NSBundle Mainbundle] urlforresource:@ "Coredatademo" withextension:@ "MOMD"];  
    //        
     _managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl];  
    // 
    nil represents Mainbundle  _    Managedobjectmodel =
     [Nsmanagedobjectmodel Mergedmodelfrombundles:nil];  
    return  
     _managedobjectmodel;}  
   

Mergedmodelfrombundles:nil connecting all the. Xcdatamodeld files in the project is a Datamodel, which is a very good way to put multiple entity in separate Xcodemodel file management, Then use this function to connect to create a datamodel, so that you can correspond to a persistentstore

3:nspersistentstorecoordinator

Connect data models to PersistentStore by setting the name, location, storage, and storage time of the data store via Persistentstorecoordinator.

The initialization method is as follows

-(Nspersistentstorecoordinator *) persistentstorecoordinator{if(_persistentstorecoordinator! =Nil) {        return_persistentstorecoordinator; } Nsurl*storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@"Coredatademo.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;}

We initialize a persistentstorecoordinator by Initwithmanagedobjectmodel, the data Model (Managedobjectmodel) is specified in the initialization method, The data model is then specified by the Addpersistentstorewithtype method as a SQLite database, and the database file path is specified by the URL.

In addition to Nssqlitestoretype can also set the following several PersistentStore

Coredata_extern nsstring * const nssqlitestoretype ns_available(_4, 3 _0);

Coredata_extern nsstring * const nsxmlstoretype ns_available(_4, NA);

Coredata_extern nsstring * const nsbinarystoretype ns_available(_4, 3_0);

Coredata_extern nsstring * const nsinmemorystoretype ns_available(_4, 3 _0);

4:nsmanagedobject: An entity object that defines the structure of the data, but he is not the data, the real data instance is the Nsmanagedobject class or his subclass, and each Nsmanagedobject object corresponds to a record in the database table.

5:nsmanagedobjectcontext

The operation of the data is all done in Managedobjectscontext.

The initialization method is as follows

-(Nsmanagedobjectcontext *) managedobjectcontext{    if (_managedobjectcontext! = Nil) {         return  _managedobjectcontext;    }         *coordinator = [self persistentstorecoordinator];     if (Coordinator! = nil)        {= [[Nsmanagedobjectcontext alloc] init];        [_managedobjectcontext setpersistentstorecoordinator:coordinator];    }     return _managedobjectcontext;}

6:nsentitydescription: Table Structure

7:nsfetchrequest: Query statement

CoreData Use Process

1: Building a data model

File->new->file->core Data->datamodel Create a new data model file

Then addentity add the entity

Entity renamed to Myentity and add name and birthday two properties for entity

2: Generate Nsmanagedobject

Editor->create Nsmanagedobject Subclass, then select entity in Datamodel and Datamodel to automatically generate our ManagedObject

@interface** birthday; @end @implementation myentity@dynamic name; @dynamic birthday; @end

3: Set Nsmanagedobjectcontext

Initialize our nsmanagedobjectcontext in a viewcontroller that needs to use CoreData storage

- (void) viewdidload{[Super Viewdidload]; Nsmanagedobjectmodel*model =[Nsmanagedobjectmodel Mergedmodelfrombundles:nil]; NSString*pathdir =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) firstobject]; NSString*path = [Pathdir stringbyappendingpathcomponent:@"Coredata.sqlite"]; NSLog (@"%@", Pathdir); Nsurl*url =[Nsurl Fileurlwithpath:path]; Nspersistentstorecoordinator*coordinator =[[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model];            [Coordinator Addpersistentstorewithtype:nssqlitestoretype Configuration:nil Url:url Options:nil Error:nil]; _managedobjectcontext=[[Nsmanagedobjectcontext alloc] init]; [_managedobjectcontext setpersistentstorecoordinator:coordinator];}

The above code will need to set Persistentstorecoordinato after initializing the Nsmanagedobjectcontext, and coordinator will need to set the Datamodel and store the file when initializing, storage mode

4: Storing Entity objects

-(Ibaction) Saveentity: (ID) Sender {myentity*entity = [Nsentitydescription insertnewobjectforentityforname:@"myentity"Inmanagedobjectcontext:_managedobjectcontext]; Entity.name=@"Zaglitao"; Entity.birthday=[NSDate Date]; Nserror*error; if(! [_managedobjectcontext save:&ERROR]) {NSLog (@"Error saving entity"); }}

We enter edit Scheme->run->arguments to add-com.apple.coredata.sqldebug 1 so that the console can print out the SQL statement

2014-11-17 10:50:44.862 datastoredemo[1749:607] CoreData:sql:BEGIN EXCLUSIVE

2014-11-17 10:50:44.863 datastoredemo[1749:607] CoreData:sql:INSERT into zmyentity (Z_PK, Z_ent, z_opt, Zbirthday, ZNAME ) VALUES (?,?,?,?,?)

2014-11-17 10:50:44.863 datastoredemo[1749:607] CoreData:sql:COMMIT

You can see that the database tables and properties created by CoreData are added with the letter Z based on our settings.

5: Querying entity objects

-(Ibaction) GetEntity: (ID) Sender {nsfetchrequest*request =[[Nsfetchrequest alloc] init]; Nsentitydescription*description = [Nsentitydescription entityforname:@"myentity"Inmanagedobjectcontext:_managedobjectcontext];    [Request Setentity:description]; Request.predicate= [Nspredicate Predicatewithformat:@"name like%@",@"Zanglitao"]; Nserror*error; Nsarray*array = [_managedobjectcontext executefetchrequest:request error:&ERROR]; NSLog (@"%@", array);}

SELECT 0, t0. Z_PK, t0. Z_opt, t0. Zbirthday, t0. Zname from zmyentity t0 WHERE nscoredatalike (t0. Zname,?, 0)

6: Change the Entity object

-(Ibaction) Updateentity: (ID) Sender {nsfetchrequest*request = [Nsfetchrequest fetchrequestwithentityname:@"myentity"]; Request.predicate= [Nspredicate Predicatewithformat:@"name like ' Zaglitao '"]; Nsarray*array =[_managedobjectcontext executefetchrequest:request Error:nil]; Myentity*entity =[Array firstobject]; Entity.name=@"Zanglitao"; Nserror*error; if(! [_managedobjectcontext save:&ERROR]) {NSLog (@"Update entity Error"); }}

2014-11-17 10:52:36.496 datastoredemo[1749:607] CoreData:sql:BEGIN EXCLUSIVE

2014-11-17 10:52:36.497 datastoredemo[1749:607] CoreData:sql:UPDATE zmyentity SET zname =?, z_opt =? WHERE Z_PK =? and z_opt =?

2014-11-17 10:52:36.497 datastoredemo[1749:607] CoreData:sql:COMMIT

7: Delete entity objects

-(Ibaction) Deleteentity: (ID) Sender {nsfetchrequest*request = [Nsfetchrequest fetchrequestwithentityname:@"myentity"]; Request.predicate= [Nspredicate Predicatewithformat:@"name like ' Zanglitao '"]; Nsarray*array =[_managedobjectcontext executefetchrequest:request Error:nil]; Myentity*entity =[Array firstobject];        [_managedobjectcontext deleteobject:entity]; Nserror*error; if(! [_managedobjectcontext save:&ERROR]) {NSLog (@"Error deleting entity"); }}

2014-11-17 10:53:00.287 datastoredemo[1749:607] CoreData:sql:BEGIN EXCLUSIVE

2014-11-17 10:53:00.287 datastoredemo[1749:607] CoreData:sql:DELETE from zmyentity WHERE z_pk =? and z_opt =?

2014-11-17 10:53:00.310 datastoredemo[1749:607] CoreData:sql:COMMIT

Set up entity relationships (one user for multiple phones)

iOS storage (2) using CoreData

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.