Core Data
Core data is a framework that appears after IOS5, which provides object-relational mapping (ORM) functionality that enables you to convert OC objects into data, store them in SQLite database files, and restore data saved in a database to OC objects. During this data operation, we do not need to write any SQL statements, which is somewhat similar to the famous Hibernate persistence framework, but the feature is definitely not hibernate powerful.
Traditional database to write data to the database, and to write SQL statement Core data to avoid the trouble of writing SQL statements
CoreData Steps to use
1. Create a model file equivalent to a database
2. Add Entity equivalent table
3. Creating entity classes as compared to model classes
4. Generate the Context association model file Build database
5. Save the object to the database
6. Getting objects from a database
7. Updating data
8. Delete Data
1. Create a model file
The so-called creation model is the indirect generation of database tables
2. Adding entities
3. Create an entity class
To create an employee entity class as an example
Generate the Context file association model file Build database
Nsmanagedobjectcontext _context = [[Nsmanagedobjectcontext alloc] init];//Model filesNsmanagedobjectmodel *model = [Nsmanagedobjectmodel mergedmodelfrombundles:Nil];//Persistent storage schedulerNspersistentstorecoordinator *store = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model];NSString*doc = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSLog(@"%@", doc);NSString*sqlitepath = [Doc stringbyappendingpathcomponent:@"Company.sqlite"];//data store type database storage path[Store Addpersistentstorewithtype:nssqlitestoretype configuration:Nilurl:[NsurlFileurlwithpath:sqlitepath] Options:NilErrorNil]; _context. Persistentstorecoordinator= store;
Save object to Database
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; employee.name = @"zhangsan"; employee.age@18; employee.height@1.89; [_context save:nil];
Open the CoreData SQL statement output switch
1.打开Product,点击EditScheme... 2.点击Arguments,在ArgumentsPassed On Launch中添加2项 1> -com.apple.CoreData.SQLDebug 21
CoreData Instance Generation entity class
#import <foundation/foundation.h> #import @interface employee : nsmanagedobject @property (nonatomic , retain) NSString * NAME; @property (nonatomic , retain) nsnumber * age; @property (nonatomic , retain) nsnumber * height; @end
#import "Employee.h"@implementation Employee@dynamic name;@dynamic age;@dynamic height;@end
Import Header File Framework
#import "ViewController.h"#import <CoreData/CoreData.h>#import "Employee.h"@interface ViewController ()@property(strong,nonatomic)NSManagedObjectContext *context;@end
CoreData Fuzzy Query
@implementation viewcontroller #pragma mark Blur query- (ibaction) Likesearcher: (ID) Sender {//EnquiryNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Employee"];//Filter //1. Query start with Wang employeesNspredicate *pre = [Nspredicate predicatewithformat:@"name Beginswith%@",@"Wang"];//2. End With SiNspredicate *pre = [Nspredicate predicatewithformat:@"name ENDSWITH%@",@"Si"];//3. Name contains GNspredicate *pre = [Nspredicate predicatewithformat:@"name CONTAINS%@",@"G"];//4.like end with SiNspredicate *pre = [Nspredicate predicatewithformat:@"name like%@",@"li*"]; Request. Predicate= Pre;//Read information Nserror*error =Nil;Nsarray*emps = [ Self. ContextExecutefetchrequest:request error:&error];if(!error) {NSLog(@"Emps:%@", Emps); for(Employee *emp in Emps) {NSLog(@"%@ %@ %@"Emp. NameEmp. AgeEmp. Height); } }Else{NSLog(@"%@", error); }}
CoreData Updating data
#pragma mark updates employee information- (ibaction) UpdateEmployee: (ID) Sender {//Change the height of Wangwu to 1.7 //1. Find Wangwu Nsarray*emps = [ Selffindemployeewithname:@"Wangwu"];//2. Update your height if(Emps. Count==1) {Employee *emp = emps[0]; Emp. Height= @1.7; }//3. Sync (save) to data[ Self. ContextSaveNil];} -(Nsarray*) Findemployeewithname: (NSString*) name{//1. Find EmployeesNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Employee"]; Nspredicate *pre = [Nspredicate predicatewithformat:@"name=%@", name]; Request. Predicate= Pre;return[ Self. ContextExecutefetchrequest:request Error:Nil];}
CoreData Deleting data
#pragma mark Delete an employee- (ibaction) Deleteemployee: (ID) Sender {[ Selfdeleteemployeewithname:@"Lisi"];} -(void) Deleteemployeewithname: (NSString*) name{//Delete Zhangsan //1. Find ZhangsanNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Employee"]; Nspredicate *pre = [Nspredicate predicatewithformat:@"name=%@", name]; Request. Predicate= Pre;//2. Delete Zhangsan Nsarray*emps = [ Self. ContextExecutefetchrequest:request Error:Nil]; for(Employee *emp in Emps) {NSLog(@"Delete employee's%@."Emp. Name); [ Self. ContextDELETEOBJECT:EMP]; }//3. Synchronize the database with the context //All operations are temporarily in memory, call the Save synchronization database[ Self. ContextSaveNil];}
CoreData Querying data
#pragma mark Read employee information- (ibaction) Reademployee: (ID) Sender {//Create a Request object (fill in the table name to query-entity Class)Nsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@"Employee"];//Filter Query //Find Zhang San and taller than 1.8Nspredicate *pre = [Nspredicate predicatewithformat:@"name=%@ and Height >%@",@"Zhangsan",@(1.8)];//request.predicate = pre; //Sort in ascending order of heightNssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@"Height"Ascending:NO];//request.sortdescriptors = @[sort]; //Paging query A total of 13 data per page Show 5 data //First page of dataRequest. Fetchlimit=5; Request. Fetchoffset=Ten;//Read information Nserror*error =Nil;Nsarray*emps = [ Self. ContextExecutefetchrequest:request error:&error];if(!error) {NSLog(@"Emps:%@", Emps); for(Employee *emp in Emps) {NSLog(@"%@ %@ %@"Emp. NameEmp. AgeEmp. Height); } }Else{NSLog(@"%@", error); }}#pragma mark to add employee information- (ibaction) AddEmployee: (ID) Sender {//Create EmployeesEmployee *EMP1 = [Nsentitydescription insertnewobjectforentityforname:@"Employee"Inmanagedobjectcontext: Self. Context];//Set employee PropertiesEmp1. Name= @"Lisi"; Emp1. Age= @ -; Emp1. Height= @2.10;//Save-operation by context Nserror*error =Nil; [ Self. Contextsave:&error];if(!error) {NSLog(@"Success"); }Else{NSLog(@"%@", error); } }
CoreData Creating a context
-(void) setupcontext{//1. Context Association Company.xcdatamodeld Model fileNsmanagedobjectcontext *context = [[Nsmanagedobjectcontext alloc] init];//Correlation model file //Create a Model object //Passing a nil associates all the model files under the bundle.Nsmanagedobjectmodel *model = [Nsmanagedobjectmodel mergedmodelfrombundles:Nil];//Persistent storage schedulerNspersistentstorecoordinator *store = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model];//Store the name of the database Nserror*error =Nil;//Get Docment directory NSString*doc = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];//The path to the database save NSString*sqlitepath = [Doc stringbyappendingpathcomponent:@"Company.sqlite"]; [Store Addpersistentstorewithtype:nssqlitestoretype configuration:Nilurl:[NsurlFileurlwithpath:sqlitepath] Options:Nilerror:&error]; Context. Persistentstorecoordinator= store; Self. Context= Context;} -(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//Create Employees for(inti =0; I <Ten; i++) {Employee *EMP1 = [Nsentitydescription insertnewobjectforentityforname:@"Employee"Inmanagedobjectcontext: Self. Context];//Set employee PropertiesEmp1. Name= [NSStringstringwithformat:@"Wangwu%d", I]; Emp1. Age= @( -+ i); Emp1. Height= @2.10;//Save-operation by context Nserror*error =Nil; [ Self. Contextsave:&error];if(!error) {NSLog(@"Success"); }Else{NSLog(@"%@", error); } } }@end
Call
- (void)viewDidLoad { [super viewDidLoad]; // 创建一个数据库 company.sqlite // 数据库要一张表 员工表 (name,age,heigt) // 往数据添加员工信息 // CoreData [self setupContext];}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS Development-CoreData Framework Data persistence