Ios:core Data Entry

Source: Internet
Author: User

Core data is an ORM framework, much like. NET Framework of EntityFramework. The basic steps to use are:

    • Introduction of Coredata.framework (Standard library) in Project properties
    • Create a new Datamodel (build *.xcdatamodeld file) in your project
    • Create entity in Datamodel
    • Generate header file for Entity (menu Editor/create nsmangedobject subclass ...)
    • Add Managedobjectcontext in the project's only delegate class (AppDelegate.h, APPDELEGATE.M) to manipulate core Data
    • Code anywhere reference Managedobjectcontext read and write data

Model: (Note: mychapter, mycontent these relationships are cascade so that child objects are deleted when the parent object is removed)

Generated header file:

/*Book.h*/@interfaceBook:nsmanagedobject@property (nonatomic, retain) NSNumber*bookId, @property (nonatomic, retain) nsstring*Name: @property (nonatomic, retain) nsstring*author, @property (nonatomic, retain) nsstring*Summary, @property (nonatomic, retain) Nsset*mychapters;@end@interfaceBook (coredatageneratedaccessors)- (void) Addmychaptersobject: (Nsmanagedobject *) value;- (void) Removemychaptersobject: (Nsmanagedobject *) value;- (void) Addmychapters: (Nsset *) values;- (void) Removemychapters: (Nsset *) values;@end/*Chapter.h*/@classBook ;@interfaceChapter:nsmanagedobject@property (nonatomic, retain) NSNumber*Chapid, @property (nonatomic, retain) nsstring*Name: @property (nonatomic, retain) NSNumber*orderId, @property (nonatomic, retain) book*Ownerbook, @property (nonatomic, retain) Nsmanagedobject*mycontent;@end/*TextContent.h*/@classChapter;@interfaceTextcontent:nsmanagedobject@property (nonatomic, retain) NSNumber*Chapid, @property (nonatomic, retain) nsstring*text; @property (nonatomic, retain) Chapter*Ownerchapter;@end

Delegate Class Code

AppDelegate.h

//AppDelegate.h#import<UIKit/UIKit.h>#import<CoreData/CoreData.h>#import "Book.h"#import "Chapter.h"#import "TextContent.h"@interfaceAppdelegate:uiresponder <UIApplicationDelegate>@property (Strong, nonatomic) UIWindow*window; @property (strong, nonatomic) Nsmanagedobjectcontext*Managedobjectcontext;@end

Appdelegate.m

@implementationappdelegate@synthesizeManagedobjectcontext =_managedobjectcontext;-(Nsmanagedobjectcontext *) managedobjectcontext{if(_managedobjectcontext! =Nil) {        return_managedobjectcontext; } _managedobjectcontext=[[Nsmanagedobjectcontext alloc]init]; //Setting the database pathNsurl *url =[[[ Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask]la    Stobject]; Nsurl*storedatabaseurl = [url urlbyappendingpathcomponent:@"Books.sqlite"]; //Create PresistentstorecoordinatorNserror *error =Nil; Nspersistentstorecoordinator*presistentstorecoordinator =[[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:[nsmanagedobjectmodel mergedModelFromBundles        : nil]]; //specifying storage type and path    if(![Presistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeDat Abaseurl Options:nil Error:&ERROR]) {NSLog (@"Error:%@", error);    } [_managedobjectcontext Setpersistentstorecoordinator:presistentstorecoordinator]; return_managedobjectcontext;}

Using _managedobjectcontext to operate core Data

//Save New Object-(void) teststore{//get context from AppdelegateAppdelegate *appdelegate = [UIApplication sharedapplication].Delegate; Nsmanagedobjectcontext*context =[Appdelegate Managedobjectcontext]; //First chapterTextcontent *content1 = [nsentitydescription insertnewobjectforentityforname:@"textcontent"Inmanagedobjectcontext:context]; Content1.chapid= [NSNumber numberwithint: -]; Content1.text=@"Hello1"; Chapter*chapter1 = (Chapter *) [nsentitydescription insertnewobjectforentityforname:@"Chapter"Inmanagedobjectcontext:context]; Chapter1.name=@"Hello1"; Chapter1.orderid= [NSNumber numberwithint:0]; Chapter1.chapid= [NSNumber numberwithint: -]; Chapter1.mycontent=Content1; //Chapter TwoTextcontent *content2 = [nsentitydescription insertnewobjectforentityforname:@"textcontent"Inmanagedobjectcontext:context]; Content2.chapid= [NSNumber numberwithint: -]; Content2.text=@"Hello2"; Chapter*chapter2 = (Chapter *) [nsentitydescription insertnewobjectforentityforname:@"Chapter"Inmanagedobjectcontext:context]; Chapter2.name=@"Hello2"; Chapter2.orderid= [NSNumber numberwithint:1]; Chapter2.chapid= [NSNumber numberwithint:101]; Chapter2.mycontent=Content2; //Book ObjectBook *book = (book *) [Nsentitydescription insertnewobjectforentityforname:@" Book"Inmanagedobjectcontext:context]; Book.bookid= [NSNumber numberwithint: -]; Book.name=@"Hello"; Book.author=@"Kitty"; Book.summary=@"Test";    [Book Addmychaptersobject:chapter1];        [Book Addmychaptersobject:chapter2]; //commit to persistent storage    if([context HasChanges]) {[Context Save:nil]; }}//Reading Objects-(void) testread{//get context from AppdelegateAppdelegate *appdelegate = [UIApplication sharedapplication].Delegate; Nsmanagedobjectcontext*context =[Appdelegate Managedobjectcontext]; //Generating a Query object (querying all data)Nsentitydescription *ENTITYDESCR = [nsentitydescription entityforname:@" Book"Inmanagedobjectcontext:context]; Nsfetchrequest*request =[[Nsfetchrequest alloc]init];        [Request SETENTITY:ENTITYDESCR]; //Execute QueryNserror *error; Nsarray*arraybooks = [Context executefetchrequest:request error:&ERROR]; //define how to sort (sort by the OrderID property of the Chapter object in the collection, ascending)Nssortdescriptor *chaptersdescriptor = [Nssortdescriptor sortdescriptorwithkey:@"orderId"Ascending:yes]; //traversing result sets     for(Book *bookincharraybooks) {                //use current object PropertiesNSLog (@"Book name =%@", Book.name); //use the collection properties of the current object to turn to an arrayNsarray *arraychapters =[Book.mychapters allobjects]; //SortArraychapters =[Arraychapters Sortedarrayusingdescriptors:[nsarray Arraywithobjects:chaptersdescriptor,nil]                ]; //iterating through a sub-array         for(Chapter *chapterincharraychapters) {NSLog (@"Chapter name =%@", Chapter.name); Textcontent*content = (textcontent*) chapter.mycontent; NSLog (@"Chapter Text =%@", Content.text); }    }}//Update Object Properties-(void) testupdate{//get context from AppdelegateAppdelegate *appdelegate = [UIApplication sharedapplication].Delegate; Nsmanagedobjectcontext*context =[Appdelegate Managedobjectcontext]; //Generate Request ObjectNsentitydescription *ENTITYDESCR = [nsentitydescription entityforname:@" Book"Inmanagedobjectcontext:context]; Nsfetchrequest*request =[[Nsfetchrequest alloc]init];        [Request SETENTITY:ENTITYDESCR]; //Execute QueryNserror *error; Nsarray*array = [Context executefetchrequest:request error:&ERROR]; //Change Object PropertiesBook * book = array[0]; Book.name=@"BOOKS"; //commit to persistent storage    if([context HasChanges]) {[Context Save:nil]; }}//Delete Object-(void) testremove{//get context from AppdelegateAppdelegate *appdelegate = [UIApplication sharedapplication].Delegate; Nsmanagedobjectcontext*context =[Appdelegate Managedobjectcontext]; //Generate Request ObjectNsentitydescription *ENTITYDESCR = [nsentitydescription entityforname:@" Book"Inmanagedobjectcontext:context]; Nsfetchrequest*request =[[Nsfetchrequest alloc]init];        [Request SETENTITY:ENTITYDESCR]; //Execute QueryNserror *error; Nsarray*array = [Context executefetchrequest:request error:&ERROR]; //traverse the Delete object, because the gatekeeper is set to cascade in the model, so the sub-object is automatically deleted     for(Book *bookinchArray)    {[Context Deleteobject:book]; }        //commit to persistent storage    if([context HasChanges]) {[Context Save:nil]; }}

Ios:core Data Entry

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.