iOS Learning Note-coredata

Source: Internet
Author: User

Brief introduction

CoreData provides an object-relational mapping (ORM) function, which, in effect, creates a "virtual object database", or it can be regarded as a comprehensive database management library.

Nsmanagedobjectcontext

A managed data context object that is primarily responsible for the interaction between the application and the database. We are using it to do the increase and deletion check operation. It records all changes that users make to the data. It has nspersistentstorecoordinator.

Property. Creating it requires setting the Nspersistentstorecoordinator.

Nspersistentstorecoordinator

Persistent Data Coordination Library for adding a persistent repository, equivalent to a database connector. That is, it is up to us to use the database for persistence or to persist with XML. We use it to set the repository type and specify the path to the repository. It has the Nsmanagedobjectmodel property.

Nsmanagedobjectmodel

Nsmanagedobjectmodel represents the model file for CoreData. There is a. xcdatamodeld file in the CoreData project, which is the CoreData model file. We do the properties of creating entities and adding entities in the. xcdatamodeld file. So all the entity information is in Nsmanagedobjectmodel.

Nsmanagedobject

Nsmanagedobject the corresponding entity, Nsmanagedobject is the entity's mapping and is CoreData managed by the data record. In other words, the data objects we manipulate directly in CoreData are Nsmanagedobject, and you can think of them as a thing, but in code we use Nsmanagedobject.

Nsentitydescripition

The entity Description class. Contains the name and attributes of the entity. You can use it to manipulate the specified entity.

Simple to use based on SQLite 1. Create a project

If you are creating a new project, tick the use Core data option

    

The appdelegate file automatically generates related code, such as the managed data context, which can be used directly without our own configuration.

Add the following code to the AppDelegate.h file:

/** * Context object, which is responsible for the interaction between the application and the database. We are using it to operate the entity, to carry out the operation of the increase and deletion check*/@property (ReadOnly, strong, nonatomic) Nsmanagedobjectcontext *Managedobjectcontext;/** * Manage the data model, representing CoreData's model files. Contains information for all entities. */@property (ReadOnly, strong, nonatomic) Nsmanagedobjectmodel *Managedobjectmodel;/** * Persistent Data Coordinator, add persistent storage pants. Set up here to use the database or the storage pants such as XML to do persistence, and the path of the storage pants*/@property (ReadOnly, strong, nonatomic) Nspersistentstorecoordinator *Persistentstorecoordinator;//saving data to the persistence layer (database)- (void) Savecontext;//application Sandbox document directory-(Nsurl *) applicationdocumentsdirectory;

In the APPDELEGATE.M file:

Saving data to the persistence layer

-(void ) Applicationwillterminate: (UIApplication *  -(void  ) Savecontext {Nsmanagedobjectcontext 
     *managedobjectcontext = Self.managedobjectcontext;  if  (managedobjectcontext!= nil) {Nserro        R  *error = nil;  if  ([managedobjectcontext haschanges] &&![ Managedobjectcontext save:&error]) {NSLog ( @ " unresolved error%@,%@  "  , error, [error userInfo]);        Abort (); }    }}

Managed data Model

-(Nsmanagedobjectmodel *) Managedobjectmodel {if(_managedobjectmodel! =Nil) {        return_managedobjectmodel; }    //specifies the. xcdatamodeld file, which will become a MOMD file after it is compiledNsurl *modelurl = [[NSBundle mainbundle] Urlforresource:@"Coredatademo"Withextension:@"MOMD"]; _managedobjectmodel=[[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; return_managedobjectmodel;}

Persistent Data Coordinator

-(Nspersistentstorecoordinator *) Persistentstorecoordinator {if(_persistentstorecoordinator! =Nil) {        return_persistentstorecoordinator; } _persistentstorecoordinator=[[Nspersistentstorecoordinator alloc] initwithmanagedobjectmodel:[self Managedobjectmodel]]; //Database PathNsurl *storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@"Coredatademo.sqlite"]; Nserror*error =Nil; NSString*failurereason =@"there is an error creating or loading the application ' s saved data."; /*addpersistentstorewithtype: Specify storage type Nssqlitestoretype: Database nsxmlstoretype:xml nsbinarystoretype: binary file Nsinmemorystoretype: Memory Form*/    if(! [_persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options: Nil error:&ERROR]) {        //Report any error we got.Nsmutabledictionary *dict =[Nsmutabledictionary dictionary]; Dict[nslocalizeddescriptionkey]=@"Failed to initialize the application ' s saved data"; Dict[nslocalizedfailurereasonerrorkey]=Failurereason; Dict[nsunderlyingerrorkey]=error; Error= [Nserror Errorwithdomain:@"Your_error_domain"Code9999Userinfo:dict]; NSLog (@"unresolved error%@,%@", error, [error userInfo]);    Abort (); }        return_persistentstorecoordinator;}

Managed data context

-(Nsmanagedobjectcontext *) managedobjectcontext { if  (_managedobjectcontext!= nil) { retu    RN   _managedobjectcontext; } nspersistentstorecoordinator  *coordinator = [self persistentstorecoordinator    ];  if  (! return   nil; } _managedobjectcontext  = [[Nsmanagedobjectcontext alloc]    Initwithconcurrencytype:nsmainqueueconcurrencytype];    [_managedobjectcontext Setpersistentstorecoordinator:coordinator];  return   _managedobjectcontext;}  

If it's not new engineering modeling, add the code

2. Adding entities

Select the. xcdatamdeld file in the project

Click

Name the entity in the right column

or double-click the default entity name to name

Click Add attribute for adding entity properties

If an entity contains another entity, such as an entity, the person also has an entity card. There is one attribute in person Card,card that also has a property person. Then there is a need to establish a relationship between two entities. If this page, click on the Editor Style button to switch.

Two entities create a relationship this way.

Check the relationship and delete rule on the right to set the deletion rules

Correlation mode cascade, one data is deleted, and the data of another entity is deleted.

Press the editor Style button to switch to another view mode, and the final two entity graphs are:

3. Generate a Nsmanagedobject subclass for each entity

The specific class name is the entity's class, which by default is the name of the entity. If you do not want to use the entity name for the class name, simply change the entity's class:

4. Inserting data
Appdelegate *appdelegate = [[UIApplication sharedapplication]Delegate]; //Get ContextNsmanagedobjectcontext *contxt =[Appdelegate Managedobjectcontext]; //creates a person object. Creates a managed Nsmanagedobject object, specifying the entity namePerson *person = [Nsentitydescription insertnewobjectforentityforname:@" Person"Inmanagedobjectcontext:contxt]; //set the person property[Person SetValue:@"Little"Forkey:@"name"]; [Person Setvalue:[nsnumber numberwithint: in] Forkey:@" Age"]; //create a Card object. Card *card = [nsentitydescription insertnewobjectforentityforname:@"Card"Inmanagedobjectcontext:contxt]; //Set card Properties[Card Setvalue:[nsnumber Numberwithint: the] Forkey:@"Num"]; //set inter-object relationships[Person Setvalue:card Forkey:@"Card"]; [Card Setvalue:person Forkey:@" Person"]; Nserror*error =Nil; /*haschanges: Determine if the data has changed Save: Save data changes and synchronize them to a persisted data file*/    if([Contxt haschanges] &&! [Contxt save:&ERROR]) {NSLog (@"Insert failed:%@,%@", Error,error.userinfo); }    Else{NSLog (@"Insert Successful"); }
5. Querying data
Appdelegate *appdelegate =[[Appdelegate alloc] init]; Nsmanagedobjectcontext*CXT =[Appdelegate Managedobjectcontext]; //Description Class for entity associations, specifying entity name acquisitionNsentitydescription *entity = [nsentitydescription entityforname:@" Person"INMANAGEDOBJECTCONTEXT:CXT]; //Data extraction Request ClassNsfetchrequest *fetchrequest =[[Nsfetchrequest alloc] init]; //The entity description is set to the request objectFetchrequest.entity =entity; //query criteria, if you want to query the full set query conditions can beFetchrequest.predicate = [Nspredicate predicatewithformat:@"name=%@",@"Xiao Ming"]; //sort, specifying the sort field and sort method. Sorted by age sequenceNssortdescriptor *sortdescriptor = [[Nssortdescriptor alloc] Initwithkey:@" Age"Ascending:yes]; //Set the sort description to the Request objectNsarray *sortdescriptors =@[sortdescriptor]; Fetchrequest.sortdescriptors=sortdescriptors; //limit the number of records to fetch data at one timeFetchrequest.fetchlimit =Ten; Nserror*error =Nil; //request query, return array to hold managed Modelmanagedobject entity objectNsarray *listdata = [CXT executefetchrequest:fetchrequest error:&ERROR];  for(Person *personinchdataList) {NSLog (@"\nname:%@\tage:%@\ncard:%@", Person.name,person.age,person.card.num); }
6. Delete data
Appdelegate *appdelegate =[[Appdelegate alloc] init]; Nsmanagedobjectcontext*CXT =Appdelegate.managedobjectcontext; Nsentitydescription*entity = [Nsentitydescription entityforname:@"Model"INMANAGEDOBJECTCONTEXT:CXT]; Nsfetchrequest*request =[[Nsfetchrequest alloc] init]; Request.entity=entity; Request.predicate= [Nspredicate Predicatewithformat:@"title=%@", Model.title]; Nserror*error =Nil; Nsarray*listdata = [Cxt executefetchrequest:request error:&ERROR]; if(Listdata.count >0) {Modelmanagedobject*modelobject =[ListData Lastobject];                [Cxt Deleteobject:modelobject]; Error=Nil; if([CXT haschanges] &&! [Cxt save:&ERROR]) {NSLog (@"failed to delete data:%@", [Error userInfo]); }        Else{NSLog (@"Delete Data successfully"); }    }
7. Modify the data
Appdelegate *appdelegate = [[UIApplication sharedapplication]Delegate]; Nsmanagedobjectcontext*contxt =[Appdelegate Managedobjectcontext]; Nsentitydescription*entity = [Nsentitydescription entityforname:@" Person"Inmanagedobjectcontext:contxt]; Nsfetchrequest*fetchrequest =[[Nsfetchrequest alloc] init]; Fetchrequest.entity=entity; Fetchrequest.predicate= [Nspredicate Predicatewithformat:@"name=%@",@"Xiao Ming"]; Nsarray*datalist =[Contxt executefetchrequest:fetchrequest Error:nil]; person*p =Datalist.lastobject; P.name=@"Little Red"; if([Contxt haschanges] &&![Contxt Save:nil]) {NSLog (@"Modification Failed"); }    Else{NSLog (@"Modification succeeded"); }

iOS Learning Note-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.