Core Data of IOS datastore

Source: Internet
Author: User

Core date is the data persistence solution introduced after ios3.0, which is officially recommended by Apple and does not require a third-party framework. The Core date is actually a package for SQLite, providing a more advanced way to persist. When you operate on a database, you do not need to use SQL statements, which means that you can manipulate the data in the database even if you do not understand the SQL statement.

The "Object Relational Mapping" (ORM) is commonly used when using database operations in various types of application development, and Core data is one such pattern. ORM is the conversion of a table in a relational database into an object in a program, but it is actually manipulating the data in the data.

In the use of core data into the database access does not need to manually create a database, the process of creating a database is completely automated by the core data framework, developers need to do is to create the model, the creation of a specific database does not need to pipe. To put it simply, Core data actually encapsulates the creation of a database, the creation of tables, the transformation of objects and tables, and greatly simplifies our operations.

Compared with SQLite, the Core date is more primitive, the operation is more complicated, the function of C is used to operate the database, but SQLite is more controllable and can cross the platform.

Let's take a look at the simple use of core data.

I. Using core Data to add entities and models

When creating a project, you can choose to use core data, and once the project is created, the relevant code is automatically added to the Appdelegate class, and a data model file is automatically generated Jrcoredata.xcdatamodeld

AppDelegate.h

  appdelegate.h//  jrcoredata////  Created by Jerei on 15-6-24.//  Copyright (c) 2015 jerehedu. All rights reserved.//#import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @interface appdelegate: Uiresponder <UIApplicationDelegate> @property (Strong, nonatomic) UIWindow *window; @property (ReadOnly, Strong, nonatomic) Nsmanagedobjectcontext *managedobjectcontext; @property (ReadOnly, Strong, Nonatomic) Nsmanagedobjectmodel *managedobjectmodel, @property (ReadOnly, Strong, nonatomic) Nspersistentstorecoordinator * persistentstorecoordinator;-(void) savecontext;-(Nsurl *) applicationdocumentsdirectory; @end

Appdelegate.m

appdelegate.m//jrcoredata////Created by Jerei on 15-6-24.//Copyright (c) 2015 jerehedu. All rights reserved.//#import "AppDelegate.h" @interface appdelegate () @end @implementation appdelegate-(BOOL) Application: (uiapplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {//Override    Point for customization after application launch. return YES;} -(void) Applicationwillresignactive: (uiapplication *) application {//Sent when the application was about to move from a Ctive to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or when the US    Er quits the application and it begins the transition to the background state. Use the This method to the pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should with this method to pause the game.} -(void) Applicationdidenterbackground: (uiapplication *) application {//Use the method to release shared Resources, save user data, invalidate timers, and store enough application state information to restore your application to    It is terminated later. If your application supports background execution, this method is called instead of Applicationwillterminate:when the User quits.} -(void) Applicationwillenterforeground: (uiapplication *) application {//called as part of the transition from the back Ground to the inactive state; Here's can undo many of the changes made on entering the background.} -(void) Applicationdidbecomeactive: (uiapplication *) application {//Restart any tasks this were paused (or not yet STA rted) While the application was inactive. If the application is previously in the background, optionally refresh the user interface.} -(void) Applicationwillterminate: (uiapplication *) application {//called when the application was about to terminate. S Ave data if appropriate.    See also Applicationdidenterbackground:. Saves changes inThe application ' s managed object context before the application terminates. [Self savecontext];} #pragma mark-core Data stack@synthesize managedobjectcontext = _managedobjectcontext; @synthesize Managedobjectmodel = _ Managedobjectmodel; @synthesize persistentstorecoordinator = _persistentstorecoordinator;-(Nsurl *) Applicationdocumentsdirectory {//The directory the application uses to store the Core Data store file.    This code uses a directory named "Com.jerehedu.JRCoreData" in the application ' s documents directory. return [[[Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask] LastObject ];} -(Nsmanagedobjectmodel *) Managedobjectmodel {//The managed object model for the application.    It is a fatal error for the application not to be able to find and load its model.    if (_managedobjectmodel! = nil) {return _managedobjectmodel; } nsurl *modelurl = [[NSBundle mainbundle] urlforresource:@ "jrcoredata" withextension:@ "MomD "];    _managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; return _managedobjectmodel;}  -(Nspersistentstorecoordinator *) Persistentstorecoordinator {//The persistent store coordinator for the application.    This implementation creates and return a coordinator, has added the store for the application to it.    if (_persistentstorecoordinator! = nil) {return _persistentstorecoordinator; }//Create the Coordinator and store _persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] In    Itwithmanagedobjectmodel:[self Managedobjectmodel]];    Nsurl *storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@ "Jrcoredata.sqlite"];    Nserror *error = nil;    NSString *failurereason = @ "There is an error creating or loading the application ' s saved data."; 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" code:9999 userinfo:dict];        Replace this with code to handle the error appropriately. Abort () causes the application to generate a crash log and terminate.        You should don't use the This function in a shipping application, although it could be useful during.        NSLog (@ "unresolved error%@,%@", error, [error userInfo]);    Abort (); } return _persistentstorecoordinator;} -(Nsmanagedobjectcontext *) Managedobjectcontext {//Returns the managed object context for the application (which)    Already bound to the persistent store coordinator for the application.) if (_managedobjectcontext! = nil) {return _managedobjectcontext;    } nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator];    if (!coordinator) {return nil;    } _managedobjectcontext = [[Nsmanagedobjectcontext alloc] init];    [_managedobjectcontext Setpersistentstorecoordinator:coordinator]; return _managedobjectcontext;} #pragma mark-core Data saving support-(void) Savecontext {nsmanagedobjectcontext *managedobjectcontext = Self.manage    Dobjectcontext;        if (managedobjectcontext! = nil) {Nserror *error = nil; if ([Managedobjectcontext haschanges] &&![ Managedobjectcontext Save:&error]) {//Replace This implementation with code to handle the error Appropria            Tely. Abort () causes the application to generate a crash log and terminate.            You should don't use the This function in a shipping application, although it could be useful during. NSLog (@ "unresolved error%@,%@", error, [Error UserinFO]);        Abort (); }}} @end

If the project does not choose to use core Data when it is created, but it needs to be used later, you will need to manually add the relevant code in the Appdelegate. Additionally, you need to manually add a data model file

When you create the data model file, you need to be aware that the file name matches the file name that is mentioned in the Managedobjectmodel method in APPDELEGATE.M.

With the data model file, you can add entities and relationships inside, essentially adding a table to the database and establishing an association between the tables. To add an entity:

Each student has a class that has multiple students in each class, so the relationship between the student and the class can be established. Building relationships:

Once you have established a relationship, you can toggle the displayed style and view the relationships between entities in a chart:

To complete the above steps, the creation of the table in the database has been completed, and using SQLite comparison, omitted the SQL statement and call the C function to manipulate the database steps, in addition, when creating the entity does not need to set the primary key, the Entity object's property type is OC type, Other entity object types in an entity are added by establishing a relationship.

After creating the entity, you can add the Nsmanagedobject subclass file, and the system can automatically add the data model classes for the entity:

Second, the implementation of database operations through code

1.   Insert a piece of data into the student table

When using core data, the Nsmanagedobjectcontext object is added to the appdelegate, and the context of this management object needs to be manipulated. During the operation, you need to get the Nsmanagedobject entity, then set the entity's property value through KVC, and finally save the data by invoking the Save method in context.

-(void) Insert {appdelegate *delegate = [[UIApplication sharedapplication] delegate]; 1.    Get context Nsmanagedobjectcontext *context = Delegate.managedobjectcontext; 2. Locate the entity structure and generate an entity object/* nsentitydescription entity description, which is the table's structure parameter 1: Table name parameter 2: who manages the instantiated object, which is the context */Nsmanagedob        ject *stu = [nsentitydescription insertnewobjectforentityforname:@ "Student" inmanagedobjectcontext:context]; Nsmanagedobject *class1 = [nsentitydescription insertnewobjectforentityforname:@ "Classes" Inmanagedobjectcontext:    Context];    [Class1 Setvalue:[nsnumber numberwithint:1] forkey:@ "c_id"];        [Class1 setvalue:@ "a Class" forkey:@ "C_name"]; 3.    Set the Entity property value [Stu Setvalue:[nsnumber numberwithint:1] forkey:@ "s_id"];    [Stu setvalue:@ "jerehedu" forkey:@ "S_name"];        [Stu Setvalue:class1 forkey:@ "S_class"]; 4.    Call context, save entity, if not successful, return error message Nserror *error;    if ([context Save:&error]) {NSLog (@ "save OK"); } else {NSLog (@ "%@", error); }}

2. Query all the data in the Student's table

  The query is similar to the insert data operation, but the steps to construct the query object, the query result set is an array, iterating the array, you can remove the query data.

-(void) SelectAll {    appdelegate *delegate = [[UIApplication sharedapplication] delegate];        Nsmanagedobjectcontext *context = Delegate.managedobjectcontext;        Nsentitydescription *stu = [nsentitydescription entityforname:@ "Student" inmanagedobjectcontext:context];        Constructs the query object    nsfetchrequest *request = [[Nsfetchrequest alloc] init];    [Request Setentity:stu];        Executes the query, returns the result set    nsarray *resultary = [context executefetchrequest:request Error:nil];        Traverse result set    for (Nsmanagedobject *enity in resultary) {        NSLog (@ "id=%i name=%@ class=%@", [[Enity valueforkey:@] S_ ID "] intvalue],[enity valueforkey:@" s_name "],[[enity valueforkey:@" S_class "] valueforkey:@" C_name "]);}    }

  3, query the student information of the specified conditions, and update

queries that specify criteria need to be represented by predicates in addition to the query object being constructed. It then iterates through the data in the query result array, making it more row and saving.

 
-(void) update{//update (found from database-update) Appdelegate *delegate = [[UIApplication    Sharedapplication] delegate];        Nsmanagedobjectcontext *context = Delegate.managedobjectcontext;        Nsentitydescription *stu = [nsentitydescription entityforname:@ "Student" inmanagedobjectcontext:context];    Nsfetchrequest *request = [Nsfetchrequest new];        [Request Setentity:stu];        Constructs a query condition equivalent to the WHERE clause nspredicate *predicate = [nspredicate predicatewithformat:@ "s_id=%i", 1];        Put the query conditions in [request setpredicate:predicate];    Execute query Nsarray *studentary = [context executefetchrequest:request Error:nil];        if (studentary.count>0) {//update the value inside Nsmanagedobject *obj = studentary[0];    [obj setvalue:@ "apple" forkey:@ "S_name"];        } [Context Save:nil]; Show [self SelectAll];} 

  4. Delete Student information for specified conditions

Before deleting, you first need to query according to the criteria, query to the data after deletion, and save.

 
-(void) delete{//delete first found, then delete appdelegate *delegate = [[UIApplication sharedappli    cation] delegate];        Nsmanagedobjectcontext *context = Delegate.managedobjectcontext;        Nsentitydescription *stu = [nsentitydescription entityforname:@ "Student" inmanagedobjectcontext:context];    Nsfetchrequest *request = [Nsfetchrequest new];        [Request Setentity:stu];        Constructs a query condition equivalent to the WHERE clause nspredicate *predicate = [nspredicate predicatewithformat:@ "s_id=%i", 1];    Put the query conditions in [request setpredicate:predicate];    Execute query nsmanagedobject *obj = [[Context executefetchrequest:request Error:nil] lastobject];        Delete if (obj) {[Context deleteobject:obj];    [Context Save:nil]; } [self SelectAll];} 
Third, summary

Core data is the Apple's official recommendation of the persistence of the method, in the process of using, do not need to import the database framework, do not need to use SQL statements to manipulate the database, completely according to object-oriented thinking, using the entity model to manipulate the database. In the process of use, it is important to note that if the model changes, you can choose to regenerate the entity class file, but the automatically generated database is not automatically updated, and you need to consider rebuilding the database and porting the data from the previous database. Core data simplifies operations, but it does not support cross-platform use, and if you want to implement cross-platform, you need to use SQLite for data persistence.

Inquiries or technical exchanges, please join the official QQ Group: (452379712)

Jerry Education
Source:http://blog.csdn.net/jerehedu/
This article is the copyright of Yantai Jerry Education Technology Co., Ltd. and CSDN Common, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Core Data of IOS datastore

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.