Core Data
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
传统的数据库要把数据写到数据库,而且要写SQL语句 Core Data 就避免了写SQL语句的麻烦了
CoreData的使用步骤
1.创建模型文件 相当于数据库
2.添加实体 相当表
3.创建实体类 相于模型类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
1.创建模型文件
所谓的创建模型就是间接生成数据库表
2.添加实体
3.创建实体类
以创建员工实体类为例
生成上下文件 关联模型文件生成数据库
NSManagedObjectContext _context = [[NSManagedObjectContext alloc] init];
// 模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",doc);
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
//数据存储的类型 数据库存储路径
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
_context.persistentStoreCoordinator = store;
保存对象到数据库
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
employee.name = @"zhangsan";
employee.age = @18;
employee.height = @1.89;
[_context save:nil];
打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
CoreData实例
生成实体类
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@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头文件框架
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee.h"
@interface ViewController ()
@property(strong,nonatomic)NSManagedObjectContext *context;
@end
CoreData模糊查询
@implementation ViewController
#pragma mark 模糊查询
- (IBAction)likeSearcher:(id)sender {
// 查询
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 过滤
// 1.查询以wang开头员工
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wang"];
// 2.以si 结尾
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"si"];
// 3.名字包含 g
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"g"];
// 4.like 以si结尾
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"li*"];
request.predicate = pre;
//读取信息
NSError *error = nil;
NSArray *emps = [self.context executeFetchRequest:request error:&error];
if (!error) {
NSLog(@"emps: %@",emps);
for (Employee *emp in emps) {
NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);
}
}else{
NSLog(@"%@",error);
}
}
CoreData 更新数据
#pragma mark 更新员工信息
- (IBAction)updateEmployee:(id)sender {
// 把wangwu的身高更改成 1.7
// 1.查找wangwu
NSArray *emps = [self findEmployeeWithName:@"wangwu"];
// 2.更新身高
if (emps.count == 1) {
Employee *emp = emps[0];
emp.height = @1.7;
}
// 3.同步(保存)到数据
[self.context save:nil];
}
-(NSArray *)findEmployeeWithName:(NSString *)name{
// 1.查找员工
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];
request.predicate = pre;
return [self.context executeFetchRequest:request error:nil];
}
CoreData 删除数据
#pragma mark 删除员工
- (IBAction)deleteEmployee:(id)sender {
[self deleteEmployeeWithName:@"lisi"];
}
-(void)deleteEmployeeWithName:(NSString *)name{
// 删除zhangsan
// 1.查找到zhangsan
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];
request.predicate = pre;
// 2.删除zhangsan
NSArray *emps = [self.context executeFetchRequest:request error:nil];
for (Employee *emp in emps) {
NSLog(@"删除员工的人 %@",emp.name);
[self.context deleteObject:emp];
}
// 3.用context同步下数据库
//所有的操作暂时都是在内存里,调用save 同步数据库
[self.context save:nil];
}
CoreData 查询数据
#pragma mark 读取员工信息
- (IBAction)readEmployee:(id)sender {
//创建一个请求对象 (填入要查询的表名-实体类)
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 过滤查询
// 查找张三 并且身高大于1.8
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@ AND height > %@",@"zhangsan",@(1.8)];
// request.predicate = pre;
//排序 以身高进行升序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
// request.sortDescriptors = @[sort];
// 分页查询 总共13条数据 每页显示5条数据
//第一页的数据
request.fetchLimit = 5;
request.fetchOffset = 10;
//读取信息
NSError *error = nil;
NSArray *emps = [self.context executeFetchRequest:request error:&error];
if (!error) {
NSLog(@"emps: %@",emps);
for (Employee *emp in emps) {
NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);
}
}else{
NSLog(@"%@",error);
}
}
#pragma mark 添加员工信息
- (IBAction)addEmployee:(id)sender {
// 创建员工
Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
// 设置员工属性
emp1.name = @"lisi";
emp1.age = @28;
emp1.height = @2.10;
//保存 - 通过上下文操作
NSError *error = nil;
[self.context save:&error];
if (!error) {
NSLog(@"success");
}else{
NSLog(@"%@",error);
}
}
CoreData 创建上下文
-(void)setupContext{
// 1.上下文 关联Company.xcdatamodeld 模型文件
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 关联模型文件
// 创建一个模型对象
// 传一个nil 会把 bundle下的所有模型文件 关联起来
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 存储数据库的名字
NSError *error = nil;
// 获取docment目录
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 数据库保存的路径
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
context.persistentStoreCoordinator = store;
self.context = context;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// 创建员工
for (int i = 0; i < 10; i++) {
Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
// 设置员工属性
emp1.name = [NSString stringWithFormat:@"wangwu %d",i];
emp1.age = @(28 + i);
emp1.height = @2.10;
//保存 - 通过上下文操作
NSError *error = nil;
[self.context save:&error];
if (!error) {
NSLog(@"success");
}else{
NSLog(@"%@",error);
}
}
}
@end
调用
- (void)viewDidLoad {
[super viewDidLoad];
// 创建一个数据库 company.sqlite
// 数据库要一张表 员工表 (name,age,heigt)
// 往数据添加员工信息
// CoreData
[self setupContext];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-02 11:06:10