IOS study notes 16 -- Core Data

Source: Internet
Author: User
Tags notification center

Core data is a powerful layer located on the SQLite database. It avoids SQL complexity and allows us to interact with the database in a more natural way. Core Data converts database rows to OC objects (Managed Objects) so that they can be operated without any SQL knowledge.

Core data is located in the model layer in the MVC design mode. When you need to store structured data on devices, you should consider using SQLite or serialization methods. Core data is a mixture of the two methods, some functions are added to provide powerful SQL capabilities, but they are just as easy to use as serialization. Core data can store objects in applications directly to the database, without complex queries, and without the need to ensure that the attribute names of objects correspond to the database Field names, all of which are completed by core data.


Core Data Core-managed object

A hosted object is a representation of the objects to be stored in the database. It can be considered as an SQL record. It usually contains some fields, these fields match the attributes of the objects to be stored in the application. After a hosted object is created, the managed object must be managed in the managed object context before it can be stored in the database.

Managed object context:

The managed object context contains all managed objects. These managed objects are ready for submission to the database. In the managed object context, you can add, modify, and delete managed objects, this layer is equivalent to the buffer between the application and the database.

Managed object table:

The managed object table describes the schema of the database for interaction between the hosted object context and the database. Managed object tables contain column Entity Descriptions. Each entity describes a database table to map managed objects to database entries.


Create a core data

Ensure that coredata is introduced. framwork framework to the project, and then create a new model file, new file -- Data Model in core data, and then name it cdjournal. xcdatamodel, here we will make a simple program to record the flow of accounts.

Next, define the database entity, select the cdjournal. xcdatamodel file to open the table Editor, click Add an object named entry, and then you can add attributes for the object and specify the Data Type of the attribute. You can also create other entities. If an entity contains another entity, you can drag and drop to establish a link, similar to an SQL foreign key. For example, you can create an author object with multiple entries. Create entities and attributes, for example:


After creating an object, you must generate a class that represents the database object so that we can represent the object in the Code. Select the entry object, select the menu editor -- create nsmanagedobject subclass, and click Create, that's done. After that, you can see that there is an entry H and M files in the project. This is the object in the core data model. The basic preparation is complete. The following is the project directory:


Now write the code to initialize the core data model.

First, declare the object required by core data in appdelegate. h. The Code is as follows:

# Import <uikit/uikit. h> // introduce coredata framework # import <coredata/coredata. h> @ classviewcontroller; @ interface appdelegate: uiresponder <uiapplicationdelegate]> @ property (strong, nonatomic) uiwindow * window; @ property (strong, nonatomic) viewcontroller * viewcontroller; // data model object @ property (strong, nonatomic) nsmanagedobjectmodel * managedobjectmodel; // context object @ property (strong, nonatomic) nsmanagedobjectcontext * managedobjectcontext; // persistent storage zone @ property (strong, nonatomic) nspersistentstorecoordinator * persistentstorecoordinator; // initialize the database used by core data-(nspersistentstorecoordinator *) persistentstorecoordinator; // initialize the value assignment function of managedobjectmodel-(nsmanagedobjectmodel *) managedobjectmodel; // The Value assignment function of managedobjectcontext-(nsmanagedobjectcontext *) managedobjectcontext; @ end

Then implement the defined method in the. M file:

-(Nsmanagedobjectmodel *) managedobjectmodel {If (managedobjectmodel! = Nil) {response;} managedobjectmodel = [[javasmergedmodelfrombundles: Nil] retain]; return managedobjectmodel;}-(response *) persistentstorecoordinator {if! = Nil) {response;} // obtain the database path nsstring * docs = [nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) lastobject]; // coredata is built on SQLite, the database name must be nsurl * storeurl = [nsurl fileurlwithpath: [docs stringbyappendingpathcomponent: @ "cdjournal. SQLite "]; nserror * error = nil; persistentstorecoordinator = [[nspersistentstorecoordinator allo C] initwithmanagedobjectmodel: [self managedobjectmodel]; If (! [Persistentstorecoordinator addpersistentstorewithtype: nssqlitestoretype configuration: Nil URL: storeurl options: Nil error: & error]) {nslog (@ "error: % @, % @", error, [error userinfo]);} returnpersistentstorecoordinator;}-(nsmanagedobjectcontext *) managedobjectcontext {If (managedobjectcontext! = Nil) {return managedobjectcontext;} nspersistentstorecoordinator * Coordinator = [self persistentstorecoordinator]; If (Coordinator! = Nil) {managedobjectcontext = [[nsmanagedobjectcontext alloc] init]; [managedobjectcontext setpersistentstorecoordinator: Coordinator];} return managedobjectcontext ;}

In addition, to ensure that the data to be stored is not lost, add the following code:

// This method defines the method to be executed when the application returns to the background, and press the Home Key for execution (scheduling in the notification center) // The purpose of this method is to store the hosted object context to the data storage area to prevent unsaved data when the program exits-(void) applicationwillterminate :( uiapplication *) application {nserror * error; If (managedobjectcontext! = Nil) {// The haschanges method checks whether there are unsaved context changes. If yes, run the Save method to save the context if ([managedobjectcontext haschanges] &! [Managedobjectcontext save: & error]) {nslog (@ "error: % @, % @", error, [error userinfo]); abort ();}}}

Then layout the XIB file and connect iboutlet and ibaction

The viewcontroller. H code is as follows:

# Import <uikit/uikit. h> # import "appdelegate. H "@ interface viewcontroller: uiviewcontroller @ property (retain, nonatomic) Comment * titletextfield; @ property (retain, nonatomic) Comment * contenttextfield; @ property (strong, nonatomic) appdelegate * mydelegate; @ property (strong, nonatomic) nsmutablearray * entries; // click the button to save the data-(ibaction) addtodb :( ID) sender; // click the button and execute the query operation-(ibaction) queryfromdb :( ID) sender; // after entering the information in uitextfield through the keyboard, click the blank area on the screen to close the keyboard operation-(ibaction) backgroundtapped :( ID) sender; @ end

The viewcontroller. m code is as follows:

# Import "viewcontroller. H "# import" entry. H "@ interfaceviewcontroller () @ end @ implementation viewcontroller @ synthesize titletextfield; @ synthesize contenttextfield; @ synthesize mydelegate = _ mydelegate; @ synthesize entries = _ entries;-(void) viewdidload {[superviewdidload]; // obtain the delegate of the current application (uiapplication sharedapplication is the context of the entire application) self. mydelegate = (appdelegate *) [[uiapplication sharedapplication] delegat E];}-(void) viewdidunload {[selfsettitletextfield: Nil]; [selfsetcontenttextfield: Nil]; [superviewdidunload]; // release any retained subviews of the main view .} -(bool) shouldautorotatetointerfaceorientation :( uiinterfaceorientation) interfaceorientation {return (interfaceorientation! = Uiinterfaceorientationportraitupsidedown);}-(void) dealloc {[titletextfieldrelease]; [contenttextfieldrelease]; [superdealloc] ;}// click the button to save data (ibaction) addtodb :( ID) sender {// Let coredata create a new object in the context (managed object) entry * entry = (Entry *) [nsentitydescription insertnewobjectforentityforname: @ "entry" inmanagedobjectcontext: self. mydelegate. managedobjectcontext]; [Entry settitle: Self. titletextfield. text]; [Entry setbody: Self. contenttextfield. text]; [Entry setcreationdate: [nsdatedate]; nserror * error; // After the hosted object is ready, call the Save method of the hosted object context to write data to the database bool issavesuccess = [self. mydelegate. managedobjectcontextsave: & error]; If (! Issavesuccess) {nslog (@ "error: % @, % @", error, [error userinfo]);} else {nslog (@ "Save successful! ") ;}} // Click the button to perform the query operation-(ibaction) queryfromdb :( ID) sender {// create a data retrieval request nsfetchrequest * request = [[nsfetchrequest alloc] init]; // you can specify the object type nsentitydescription * entity = [nsentitydescription entityforname: @ "entry" inmanagedobjectcontext: Self. mydelegate. managedobjectcontext]; // sets the request entity [Request setentity: entity]; // specifies the way nssortdescriptor * sortdescriptor = [[nssortdescriptor alloc] initwithkey :@" Creationdate "ascending: No]; nsarray * sortdescriptions = [[nsarray alloc] conditions: conditions, nil]; [Request conditions: sortdescriptions]; [sortdescriptions release]; [sortdescriptor release]; nserror * error = nil; // execute the data retrieval request and return the array nsmutablearray * mutablefetchresult = [self. mydelegate. managedobjectcontext executefetchrequest: Request error: & error] mutablecopy]; If (mutablefetchres Ult = nil) {nslog (@ "error: % @, % @", error, [error userinfo]);} self. entries = mutablefetchresult; nslog (@ "The Count of entry: % I", [self. entriescount]); For (Entry * entry inself. entries) {nslog (@ "title: % @ --- Content: % @ --- Date: % @", entry. title, entry. body, entry. creationdate);} [mutablefetchresult release]; [request release];} // update operation-(void) updateentry :( entry *) entry {[Entry settitle: Self. titletextfield. Text]; [Entry setbody: Self. contenttextfield. text]; [Entry setcreationdate: [nsdatedate]; nserror * error; bool isupdatesuccess = [self. mydelegate. managedobjectcontextsave: & error]; If (! Isupdatesuccess) {nslog (@ "error: % @, % @", error, [error userinfo]) ;}// delete operation-(void) deleteentry :( entry *) entry {[self. mydelegate. managedobjectcontext deleteobject: entry]; [self. entriesremoveobject: entry]; nserror * error; If (! [Self. mydelegate. managedobjectcontext save: & error]) {nslog (@ "error: % @, % @", error, [error userinfo]);} // after entering the field in uitextfield through the keyboard, click the blank area on the screen to close the keyboard operation-(ibaction) backgroundtapped :( ID) sender {[titletextfield resignfirstresponder]; [contenttextfield resignfirstresponder];} @ end

Finally, run and fill in the Data. Click Add to add the data.

After adding a few more data entries, click query to view the output query results. The output results in the command line are as follows:


The above is a simple use of core data. Core Data has many other functions. Here we will not list them one by one. For details, refer to Apple's official documentation.

To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group


Welcome to my Sina Weibo chat: @ Tang Ren _ Ryan

Related Article

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.