封装CoreManager类
@implementation CoreDataManager
{
//上下文
NSManagedObjectContext *_ctx;
}
//单例
+(instancetype)sharedManager
{
static CoreDataManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[CoreDataManager alloc] init];
});
return manager;
}
//初始化时,同事初始化相关的
-(instancetype)init
{
self = [super init];
if (self) {
//初始化上下文对象
//1.关联实体描述文件(User.xcdatamodeld)
//扩展名写@“momd”
NSString *path = [[NSBundle mainBundle] pathForResource:@"GuoFuBao" ofType:@"momd"];
NSURL *url = [NSURL fileURLWithPath:path];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
//2.关联数据库文件
NSPersistentStoreCoordinator *coor = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
//数据库文件的路径
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/gfb.sqlite"];
NSLog(@"path=%@",dataPath);
NSURL *dataUrl = [NSURL fileURLWithPath:dataPath];
//CoreData管理的数据库文件升级时传参
NSDictionary *optionDict = @{NSMigratePersistentStoresAutomaticallyOption:[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption:[NSNumber numberWithBool:YES]};
[coor addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dataUrl options:optionDict error:nil];
//3.上下文对象
_ctx = [[NSManagedObjectContext alloc] init];
_ctx.persistentStoreCoordinator = coor;
}
return self;
}
增(插入)
//插入数据
- (IBAction)insertData{
NSLog(@"插入数据");
//创建模型数据模型
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedContext];
student.name = @"张三2";
student.id = @(11);
Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:self.managedContext];
book.bookID = @(121);
book.bookName = @"<老人与海2>";
student.book = book;
Student *student2 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedContext];
student2.name = @"李四2";
student2.id = @(23);
Book *book2 = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:self.managedContext];
book2.bookID = @(242);
book2.bookName = @"<飞鸟集2>";
student2.book = book2;
//保存,用 save 方法
NSError *error = nil;
BOOL success = [self.managedContext save:&error];
if (!success) {
[NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];
}
}
删(删除)
//删除
- (IBAction)removeData:(id)sender{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
//查到到你要删除的数据库中的对象
NSPredicate *predic = [NSPredicate predicateWithFormat:@"name = %@",@"张三2"];
request.predicate = predic;
//请求数据
NSArray *objs = [self.managedContext executeFetchRequest:request error:nil];
for (Student *stu in objs) {
[self.managedContext deleteObject:stu];
}
[self.managedContext save:nil];
}
查
/读取数据库文件
- (IBAction)readData{
NSLog(@"读取数据");
dispatch_async(dispatch_get_main_queue(), ^{
// 初始化一个查询请求
// NSFetchRequest *request = [[NSFetchRequest alloc] init];
// 设置要查询的实体
// request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedContext];
//以上代码简写成下边
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 设置排序(按照age降序)
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sort];
// 设置条件过滤(搜索name中包含字符串"zhang"的记录,注意:设置条件过滤时,数据库SQL语句中的%要用*来代替,所以%Itcast-1%应该写成*zhang*)
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];
// request.predicate = predicate;
// 执行请求
NSError *error = nil;
NSArray *objs = [self.managedContext executeFetchRequest:request error:&error];
if (error) {
[NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
}
NSLog(@"-----------------------------------");
// 遍历数据
int index = 0;
for (NSManagedObject *obj in objs) {
NSLog(@"%d---name=%@", index++,[obj valueForKey:@"name"]);
}
for (Student *stu in objs) {
Book *book = stu.book;
NSLog(@"%@---name=%@", stu.name,book.bookName);
}
});
}
改(更新)
//更新数据
- (IBAction)modifyData{
// 如果是想做更新操作:只要在更改了实体对象的属性后调用[context save:&error],就能将更改的数据同步到数据库
//先从数据库中取出所有的数据,然后从其中选出要修改的那个,进行修改,然后保存
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
//设置过滤条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"李四2"];
request.predicate = pre;
NSError *error = nil;
NSArray *objs = [self.managedContext executeFetchRequest:request error:&error];
if (error) {
[NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
}
// 2.更新身高
for (Student *stu in objs) {
stu.name = @"被修改的新名字";
}
//保存,用 save 方法
BOOL success = [self.managedContext save:&error];
if (!success) {
[NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];
}
}
/////////////////////****************************************************************************************/////////////////////
//已存在的项目,使用 CoreData ,步骤:
来自: http://blog.csdn.net/wolaikanyanhau/article/details/50752704
一. 首先需要引入CoreData FrameWork . 点击Build Phases,在下面的界面中找到LinkBinary With Libraries。
二. 创建 DataModel
三. 在 AppDelagate 加入相关代码(或者自己创建工具类)
四. 在DataModel中创建相应实体Entity
五.创建托管类模型.h.m 文件:(选中momd, 菜单栏 Editor--> NSManagedObject Subclass)
//创建完.h.m 文件后,可能会报错,在链接库哪里删掉. m 或者删掉 momd 文件即可修复 链接: http://www.jianshu.com/p/8dd276722151
/////////////////////****************************************************************************************/////////////////////
//CoreData 数据库升级
来自: http://blog.csdn.net/SoundsGood/article/details/49365491
如果IOS App 使用到CoreData,并且在上一个版本上有数据库更新(新增表、字段等操作),那在覆盖安装程序时就要进行CoreData数据库的迁移,具体操作如下:
1.选中你的mydata.xcdatamodeld文件,选择菜单editor->Add Model Version 比如取名:mydata2.xcdatamodel
2.设置当前版本
选择上级mydata.xcdatamodeld ,在inspector中的Versioned Core Data Model选择Current模版为mydata2
3.修改新数据模型mydata2,在新的文件上添加字段及表
4.删除原来的类文件,重新生成下类。