IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)

 

1>什么是CoreData

Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
 
 
 
2>CoreData的使用步骤
 
1.创建模型文件
2.添加实体
3.创建实体类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
 
3>打开CoreData的SQL语句输出开关
 
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
   1> -com.apple.CoreData.SQLDebug
   2> 1
 

一、CoreData基本使用-增删改查和表关联

  1 //
  2 //  ViewController.m
  3 //  IOS_0121_CoreData
  4 //
  5 //  Created by ma c on 16/1/21.
  6 //  Copyright © 2016年 博文科技. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #import <CoreData/CoreData.h>
 11 #import "Employee.h"
 12 #import "Department.h"
 13 
 14 @interface ViewController ()
 15 
 16 @property (nonatomic, strong) NSManagedObjectContext *context;
 17 
 18 @end
 19 
 20 @implementation ViewController
 21 
 22 - (void)viewDidLoad {
 23     [super viewDidLoad];
 24     //1.创建模型文件(相当于数据库中的表)
 25     //2.添加实体(一张表)
 26     //3.创建实体类(相当于模型)
 27     //4.生成上下文,关联模型文件生成数据库
 28     
 29     //上下文
 30     self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
 31     //模型数据文件
 32     NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
 33     
 34     //持久化存储器
 35     //把数据保存到一个文件,而不是内存
 36     NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
 37     //数据名字和路径
 38     NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 39     NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
 40     NSLog(@"%@",sqlitePath);
 41     
 42     NSURL *url = [NSURL fileURLWithPath:sqlitePath];
 43     [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
 44     
 45     self.context.persistentStoreCoordinator = store;
 46     
 47 }
 48 //数据库操作ADUQ (ADD、Delete、Update、Query)
 49 #pragma mark - 添加员工
 50 - (IBAction)addEmployee
 51 {
 52     Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
 53     
 54     emp.name = @"bowen";
 55     emp.height = @"180";
 56     emp.birthday = [NSDate date];
 57     
 58     
 59     //直接保存
 60     NSError *error = nil;
 61     [self.context save:&error];
 62     
 63     if (error) {
 64         NSLog(@"%@",error);
 65     }
 66 }
 67 
 68 #pragma mark - 查询员工
 69 - (IBAction)searchEmployee
 70 {
 71     //1.NSFetchRequest 抓取请求对象
 72     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
 73     //2.设置过滤条件
 74     NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
 75     request.predicate = pre;
 76     //3.排序
 77     NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
 78     request.sortDescriptors = @[heightSort];
 79     //4.执行请求
 80     NSError *error = nil;
 81     NSArray *emps = [self.context executeFetchRequest:request error:&error];
 82     
 83     if (error) {
 84         NSLog(@"%@",error);
 85     }
 86     
 87     for (Employee *emp in emps) {
 88         NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
 89     }
 90 }
 91 
 92 #pragma mark - 更新员工
 93 - (IBAction)updateEmployee
 94 {
 95     //1.查找
 96     //获取对象
 97     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
 98     //设置过滤条件
 99     NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
100     request.predicate = pre;
101     //执行请求
102     NSArray *emps = [self.context executeFetchRequest:request error:nil];
103     
104     //2.更新
105     for (Employee *emp in emps) {
106         emp.height = @"200";
107     }
108     //3.保存
109     [self.context save:nil];
110 }
111 
112 #pragma mark - 删除员工
113 - (IBAction)deleteEmployee
114 {
115     //1.查找
116     //获取对象
117     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
118     //设置过滤条件
119     NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
120     request.predicate = pre;
121     //执行请求
122     NSArray *emps = [self.context executeFetchRequest:request error:nil];
123     
124     //2.删除
125     for (Employee *emp in emps) {
126         [self.context deleteObject:emp];
127     }
128     
129     //3.保存
130     [self.context save:nil];
131 }
132 
133 #pragma mark - 表关联
134 - (IBAction)AddRelationship
135 {
136     //创建两个部门:IOS、Android
137     Department *IOSDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
138     IOSDepart.departNo = @"001";
139     IOSDepart.name = @"IOS";
140     IOSDepart.createDate = [NSDate date];
141     
142     Department *AndroidDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
143     AndroidDepart.departNo = @"002";
144     AndroidDepart.name = @"Android";
145     AndroidDepart.createDate = [NSDate date];
146     
147     //创建两个员工:bowen1,bowen2
148     Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
149     emp1.name = @"bowen1";
150     emp1.height = @"180";
151     emp1.birthday = [NSDate date];
152     emp1.depart = IOSDepart;
153     
154     Employee *emp2 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
155     emp2.name = @"bowen2";
156     emp2.height = @"180";
157     emp2.birthday = [NSDate date];
158     emp2.depart = AndroidDepart;
159     
160     //保存
161     [self.context save:nil];    
162 }
163 
164 
165 - (IBAction)searchRelationship
166 {
167     //读取IOS部门员工
168     
169     //1.NSFetchRequest 抓取请求对象
170     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
171     //2.设置过滤条件
172     NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"IOS"];
173     request.predicate = pre;
174     //3.执行请求
175     NSError *error = nil;
176     NSArray *emps = [self.context executeFetchRequest:request error:&error];
177     
178     if (error) {
179         NSLog(@"%@",error);
180     }
181     
182     for (Employee *emp in emps) {
183         NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
184     }
185 
186 }
187 
188 - (void)didReceiveMemoryWarning {
189     [super didReceiveMemoryWarning];
190     // Dispose of any resources that can be recreated.
191 }
192 
193 @end

 三、分页查询和模糊查询

  1 //
  2 //  ViewController.m
  3 //  IOS_0121_CoreData
  4 //
  5 //  Created by ma c on 16/1/21.
  6 //  Copyright © 2016年 博文科技. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #import <CoreData/CoreData.h>
 11 #import "Employee.h"
 12 #import "Department.h"
 13 
 14 @interface ViewController ()
 15 
 16 @property (nonatomic, strong) NSManagedObjectContext *context;
 17 
 18 @end
 19 
 20 @implementation ViewController
 21 
 22 - (void)viewDidLoad {
 23     [super viewDidLoad];
 24     //1.创建模型文件(相当于数据库中的表)
 25     //2.添加实体(一张表)
 26     //3.创建实体类(相当于模型)
 27     //4.生成上下文,关联模型文件生成数据库
 28     
 29     //上下文
 30     self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
 31     //模型数据文件
 32     NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
 33     
 34     //持久化存储器
 35     //把数据保存到一个文件,而不是内存
 36     NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
 37     //数据名字和路径
 38     NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 39     NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
 40     NSLog(@"%@",sqlitePath);
 41     
 42     NSURL *url = [NSURL fileURLWithPath:sqlitePath];
 43     [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
 44     
 45     self.context.persistentStoreCoordinator = store;
 46     
 47 }
 48 //数据库操作ADUQ (ADD、Delete、Update、Query)
 49 #pragma mark - 添加员工
 50 - (IBAction)addEmployee
 51 {
 52 
 53     for (int i = 0; i < 15; i++) {
 54         Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
 55         emp.name = [NSString stringWithFormat:@"bowen%d",i];
 56         emp.height = [NSString stringWithFormat:@"%d",180+i];
 57         emp.birthday = [NSDate date];
 58         
 59     }
 60 
 61     //直接保存
 62     NSError *error = nil;
 63     [self.context save:&error];
 64     
 65     if (error) {
 66         NSLog(@"%@",error);
 67     }
 68 }
 69 
 70 #pragma mark - 分页查询
 71 - (IBAction)pagingAndQuerying
 72 {
 73     //1.NSFetchRequest 抓取请求对象
 74     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
 75     
 76     //2.排序
 77     NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
 78     request.sortDescriptors = @[heightSort];
 79     
 80     //3.分页查询
 81     //分页的起始索引
 82     request.fetchOffset = 12;
 83     //分页的条数
 84     request.fetchLimit = 6;
 85     
 86     //4.执行请求
 87     NSError *error = nil;
 88     NSArray *emps = [self.context executeFetchRequest:request error:&error];
 89     
 90     if (error) {
 91         NSLog(@"%@",error);
 92     }
 93     
 94     for (Employee *emp in emps) {
 95         NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
 96     }
 97 }
 98 
 99 - (IBAction)fuzzyQuery
100 {
101     //1.NSFetchRequest 抓取请求对象
102     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
103     
104     //2.排序
105     NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
106     request.sortDescriptors = @[heightSort];
107     
108     //3.模糊查询
109     //名字以“bowen1”开头
110     //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"bowen1"];
111     //request.predicate = pre;
112     
113     //名字以“1”结尾
114     //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
115     //request.predicate = pre;
116     
117     //名字包含“wen1”结尾
118     //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"1"];
119     //request.predicate = pre;
120     
121     //like
122     //名字以“1”结尾
123     //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wen14"];
124     //request.predicate = pre;
125     
126     //名字以“bowen2”开头
127     NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"bowen2*"];
128     request.predicate = pre;
129 
130 
131     //4.执行请求
132     NSError *error = nil;
133     NSArray *emps = [self.context executeFetchRequest:request error:&error];
134     
135     if (error) {
136         NSLog(@"%@",error);
137     }
138     
139     for (Employee *emp in emps) {
140         NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
141     }
142 }
143 
144 @end

 三、创建多个数据库

  1 //
  2 //  ViewController.m
  3 //  IOS_0121_CoreData
  4 //
  5 //  Created by ma c on 16/1/21.
  6 //  Copyright © 2016年 博文科技. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #import <CoreData/CoreData.h>
 11 #import "Employee.h"
 12 #import "Status.h"
 13 
 14 @interface ViewController ()
 15 
 16 @property (nonatomic, strong) NSManagedObjectContext *companyContext;
 17 @property (nonatomic, strong) NSManagedObjectContext *weibocontext;
 18 
 19 
 20 @end
 21 
 22 @implementation ViewController
 23 
 24 - (void)viewDidLoad {
 25     [super viewDidLoad];
 26     
 27     //一个数据库对应着一个上下文
 28     self.companyContext = [self setupContextWithModelName:@"Company"];
 29     self.weibocontext = [self setupContextWithModelName:@"weibo"];
 30     
 31     
 32 }
 33 
 34 //根据模型文件返回上下文
 35 - (NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName
 36 {
 37     //1.创建模型文件(相当于数据库中的表)
 38     //2.添加实体(一张表)
 39     //3.创建实体类(相当于模型)
 40     //4.生成上下文,关联模型文件生成数据库
 41     
 42     //上下文
 43     NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
 44     
 45     //模型数据文件
 46     //使用下面的方法,如果boundles为空,会把boundles里面所有的模型文件的表都放在一个数据库中
 47     //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
 48     
 49     NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
 50     
 51     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
 52     NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
 53     
 54     //持久化存储器
 55     //把数据保存到一个文件,而不是内存
 56     NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
 57     
 58     //数据名字和路径
 59     NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 60     
 61     NSString *sqlliteName = [NSString stringWithFormat:@"%@.sqllite",modelName];
 62     
 63     NSString *sqlitePath = [path stringByAppendingPathComponent:sqlliteName];
 64     NSLog(@"%@",sqlitePath);
 65     
 66     NSURL *url = [NSURL fileURLWithPath:sqlitePath];
 67     [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
 68     
 69     context.persistentStoreCoordinator = store;
 70     
 71     return context;
 72 
 73 }
 74 //数据库操作ADUQ (ADD、Delete、Update、Query)
 75 #pragma mark - 添加
 76 - (IBAction)add
 77 {
 78     Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.companyContext];
 79     emp.name = @"bowen";
 80     emp.height = @"180";
 81     emp.birthday = [NSDate date];
 82     
 83     Status *status = [NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:self.weibocontext];
 84     status.text = @"回家";
 85     status.createDate = @"2015-01-28";
 86     
 87     [self.companyContext save:nil];
 88     [self.weibocontext save:nil];
 89     
 90     
 91     
 92     
 93     
 94 
 95 }
 96 
 97 #pragma mark - 查询
 98 - (IBAction)querying
 99 {
100     
101 }
102 
103 
104 @end

 

你可能感兴趣的:(IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库))