Use of Ios-coredata

Source: Internet
Author: User

Today learned the use of coredata, here to do a note also for the convenience of future inquiries.
Core data is a framework that appears after IOS5, which provides object-relational mapping (ORM) functionality (Android's most commonly used framework xutils dbutils is also used to manage data), that is, the ability to convert OC objects into data, Saved in the SQLite database file, you can also restore the data saved in the database to OC objects.
Key phrases used by CoreData

Test code:

#import "ViewController.h" #import <CoreData/CoreData.h> #import "Person.h" #import "School.h"  @interface viewcontroller () {    //Context ObjectNsmanagedobjectcontext *_context;}@end @implementation viewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib.    //Initialize context object_context = [[Nsmanagedobjectcontext alloc] init];//Context Associated database    //model Model FileNsmanagedobjectmodel *model = [Nsmanagedobjectmodel mergedmodelfrombundles:Nil];//Persistence of storage SchedulerNspersistentstorecoordinator *store = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model];//Database save path    NSString*doc = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSString*sqlitepath = [Doc stringbyappendingpathcomponent:@"Person.db"];NSLog(@"Sqlitepath:%@", Sqlitepath);//Tell CoreData the name and path of the database[Store Addpersistentstorewithtype:nssqlitestoretype configuration:Nilurl:[NsurlFileurlwithpath:sqlitepath] Options:NilErrorNil]; _context. Persistentstorecoordinator= store;}#pragma mark to save the data- (ibaction) Save: (ID) Sender {//Save Table Association data    //creation of two schools Ios,androdSchool *iosschool = [Nsentitydescription insertnewobjectforentityforname:@"School"Inmanagedobjectcontext:_context]; Iosschool. Name= @"iOS School"; Iosschool. Num= @"1001"; Iosschool. Createdata= [NSDateDate];//Create Android entity classSchool *androidschool = [Nsentitydescription insertnewobjectforentityforname:@"School"Inmanagedobjectcontext:_context]; Androidschool. Name= @"Android School"; Androidschool. Num= @"1002"; Androidschool. Createdata= [NSDateDate];//Create two people Zhang San belong to iOS school, John Doe data Android School     for(inti =0; I < the; i++) {Person *iosperson = [Nsentitydescription insertnewobjectforentityforname:@"Person"Inmanagedobjectcontext:_context]; Iosperson. Name= [NSStringstringwithformat:@"Zhang San%d", I]; Iosperson. Height= @(1.50+ i); Iosperson. Birthday= [NSDateDate]; Iosperson. School= Iosschool; } Person *androidperson = [Nsentitydescription insertnewobjectforentityforname:@"Person"Inmanagedobjectcontext:_context]; Androidperson. Name= @"John Doe"; Androidperson. Height= @1.85; Androidperson. Birthday= [NSDateDate]; Androidperson. School= Androidschool; [_context Save:Nil];///////By Nsentitydescription Insert method to obtain an associated object//person *mperson = [nsentitydescription insertnewobjectforentityforname:@ ' person ' inmanagedobjectcontext:_ Context];////To add an attribute to the acquired object//Mperson.name = @ "Harry";//mperson.height = @1.79;//Mperson.birthday = [NSDate date];//    //// Call the Save method of _context to save the data//[_context Save:nil];}#pragma mark reads the data- (ibaction) Read: (IDSender {Nsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Person"]; Request. Fetchoffset=0; Request. Fetchlimit=6; Request. Sortdescriptors= @[[nssortdescriptor sortdescriptorwithkey:@"Height"Ascending:YES]];what does//beginswith start with?    what does//endswith end with?    //contains containsRequest. Predicate= [Nspredicate predicatewithformat:@"name CONTAINS%@",@"1"];//Use like    //Zhang San 1* starts with 31    //* Zhang 31 with the end of Zhang 31Request. Predicate= [Nspredicate predicatewithformat:@"name like%@",@"31 *"];Nsarray*array = [_context executefetchrequest:request error:Nil]; for(person *mperson in array) {NSLog(@"Name:%@, Height:%@, School:%@", Mperson. Name, Mperson. Height, Mperson. School. Name); }////fetchrequest Fetch Request Object//Nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@ "person"];//    //// limit crawl conditions//Nspredicate *predicate = [nspredicate predicatewithformat:@ "name =%@", @ "John Doe"];//request.predicate = predicate;//    /// sort//Nssortdescriptor *sort = [nssortdescriptor sortdescriptorwithkey:@ "height" ascending:yes];//request.sortdescriptors = @[sort];//    //// Execute FETCH request//Nsarray *requestarray = [_context executefetchrequest:request error:nil];//for (person *mperson in Requestarray) {//NSLog (@ "Name:%@, Height:%@, Birthday:%@", mperson.name,mperson.height,mperson.birthday);//    }}#pragma mark Update data- (ibaction) Update: (ID) Sender {//Get the Nsmanagedobject object to be updated firstNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Person"]; Request. Predicate= [Nspredicate predicatewithformat:@"name =%@",@"Harry"];//data to be queried    Nsarray*array = [_context executefetchrequest:request error:Nil];//Change the data to the query     for(person *mperson in array) {Mperson. Name= @"Li Liu"; Mperson. Height= @1.99; }//Save[_context Save:Nil];}#pragma mark Delete data- (ibaction) Delete: (ID) Sender {//Delete data also need to first get the Nsmanagedobject object that needs to be deletedNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Person"];//Request.predicate = [nspredicate predicatewithformat:@ "name =%@", @ "Li Liu"];    Nsarray*array = [_context executefetchrequest:request error:Nil];//Get to data and call DeleteObject to delete Nsmanagedobject object     for(person *mperson in array)    {[_context Deleteobject:mperson]; }//Save Changes[_context Save:Nil];} - (void) Didreceivememorywarning {[SuperDidreceivememorywarning];//Dispose of any resources, can be recreated.}@end

Specific reference Li Mingjie Teacher Blog: http://blog.csdn.net/q199109106q/article/details/8563438/#t4

Demo Address: http://download.csdn.net/detail/u011068996/8808331

Use of Ios-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.