做iOS开发这么久了,还没写过coredata的demo呢,项目也从来没用上(公司项目从来不使用这东西,自己的项目也没用,有FMDB或者其他),去年面试的时候有家公司面试题好多题都围绕从coreData的东西,今天想起来了,就学习一下。以下代码参考此文
#import "ViewController.h"
#import "Person.h"
@interface ViewController () <UITableViewDelegate,UITableViewDataSource> {
UITableView *_tableView;
NSMutableArray *_dataArray;
UITextField *_nameTextField;
UITextField *_ageTextField;
NSManagedObjectContext *_context; //上下文对象 我们对数据库的操作都是通过这个上下对象进行的
int _selectedRow; //记录选择哪一个cell
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self readyCoreData];
[self createUI];
}
//准备CoreData方法
- (void)readyCoreData {
//1.1创建momd(编译后的扩展名)文件路径 1.2在这个文件中创建Person模型(实体) 1.3创建与实体(模型)对应的数据模型类,此类必须继承自NSManagedObject
NSString *path = [[NSBundle mainBundle] pathForResource:@"CoreDataDemo" ofType:@"momd"];
//在操作之前 别忘记导入CorData.framework 通过path转url对象,将momd文件中的所有的模型(实体)取出放入到NSManagedObjectModel创建的对象中
//作用:添加实体的属性,建立属性之间的关系
NSManagedObjectModel *objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
//2.准备数据库路径 最后后缀db 或者rdb都可以
NSString *dataPath = [NSString stringWithFormat:@"%@/Documents/myCoreData.db",NSHomeDirectory()];
NSLog(@"dataPath:%@",dataPath);
//3.创建持久化存储协调器 相当于数据库的连接器
//作用:设置数据存储的名字,位置,存储方式和存储时机
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objectModel];
//4.关联数据库
//4.1 关联类型 在iOS开发中一般都是SQLite (轻量级 一般用于小型移动设备)4.2配置nil 写默认即可 4.3数据库路径(字符串路径转url对象)4.4相关模式(操作) nil 4.5错误信息error对象
NSError *error = nil;
NSPersistentStore *store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:&error];
//判断持久化存储对象是否为空,如果为空说明数据库创建失败
if (store == nil) {
NSLog(@"错误信息:%@",error.localizedDescription); //打印报错信息
}
//5.创建上下文对象 取数据(通过CoreData将数据从数据库取出)
_context = [[NSManagedObjectContext alloc] init];
//将上下文的持久化协调器指定到创建的属性中 (设置上下文对象的协调器)
_context.persistentStoreCoordinator = coordinator;
//查
//创建查找类,获取查找请求对象,相当于查询语句 根据实体名字Person得到请求对象
// 如果想用CoreData管理这个Person类创建出来的对象,必须继承自NSManagedObject,否则CoreData无法操作此类创建出来的对象
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
//通过上下文对象执行请求 返回一个数组类型
NSArray *array = [_context executeFetchRequest:request error:nil];
NSLog(@"array count:%ld",array.count);
//通过数组创建数组的类方法 初始化_dataArray成员变量
_dataArray = [NSMutableArray arrayWithArray:array];
}
//增删改查
- (void)buttonClicked:(UIButton *)button {
int tag = (int)button.tag - 100;
switch (tag) {
case 0:
{
//增加一个数据模型对象(实体结构对象或实体对象)
/*
第一个参数:增加数据对应的模型(增加一个新的数据 根据名字取)
第二个参数:上下文对象 注:开发中可以创建多个上下文对象管理不同的数据库,一定保证对应好哪一个上下文对象
*/
Person *Person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
//分别设置名字和年龄
Person.name = _nameTextField.text;
Person.age = [NSNumber numberWithInteger:[_ageTextField.text integerValue]];
NSError *error = nil;
//通过上下文对象 调用保存这个方法 传入参数error对象的地址 写入数据库
BOOL ret = [_context save:&error];
if (ret) { //ret为真 保存成功 否则失败
NSLog(@"保存成功");
//将Person对象放入到对应的数据 最好刷新表
[_dataArray addObject:Person];
[_tableView reloadData];
}else {
NSLog(@"保存失败:%@",error);
}
}
break;
case 1:
{
//取点击哪个Person(点击哪个cell)
Person *Person = _dataArray[_selectedRow];
//从数据库中删除对象(模型)注:这里的删除操作只是在数据库中给了一个删除标记,并没有实际删除数据
[_context deleteObject:Person];
BOOL ret = [_context save:nil];
if (ret) {
NSLog(@"删除成功");
//从数组中删除数组元素(Person对象)
[_dataArray removeObjectAtIndex:_selectedRow];
//刷新表
[_tableView reloadData];
}else {
NSLog(@"删除失败");
}
}
break;
case 2:
{
//获取请求对象 理解为sqlite语句
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//首先通过NSEntityDescription创建实体对象 ,第一个参数实体名字 第二个参数上下文对象 然后给请求对象设置实体
[request setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:_context]];
//谓语类 通过谓语指定查询类型 类似于FMDB where条件 这里是通过类方法格式化形式创建
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = 'Aa'"];
//AND
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = 'As' AND age = 0"];
//OR
//Sql语句 FMDB里和这里谓语条件通用 通常提交都和删除、修改、查询结合使用
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = 'As' OR age = 28"];
//给请求对象设置谓语条件 如果不设置谓语条件会将所有数据修改
[request setPredicate:predicate];
//执行请求 返回数组
NSArray *array = [_context executeFetchRequest:request error:nil];
for (Person *Person in array) {
Person.name = @"不知道";
Person.age = [NSNumber numberWithInt:8];
}
//保存(写回)数据库,必须要保存数据库,否则下次进入应用没有修改
[_context save:nil];
//刷新表
[_tableView reloadData];
//遍历打印一下
for (Person *Person in _dataArray) {
NSLog(@"%@",Person.name);
}
}
break;
case 3:
{
//查
//根据实体名字得到(创建)请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
//创建谓语条件对象
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = '不知道'"];
//like 像 属于一种模糊 开发中经常以什么名字开头去查询 这时候用到like , *代表任意并且B后面不管多少个字符
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like 'Be*'"];
//以a结尾的查询
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '*a'"];
//order by 或者group by
//名字包含有a的查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '*a*'"];
//给请求对象设置谓语条件对象
request.predicate = predicate;
//执行请求
NSArray *array = [_context executeFetchRequest:request error:nil];
for (Person *Person in array) {
NSLog(@"name:%@ age:%@",Person.name,Person.age);
}
}
break;
default:
break;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
//从数组中去Person模型对象
Person *Person = [_dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@ 年龄:%@",Person.name,Person.age];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//记录row (cell)
_selectedRow = (int)indexPath.row;
}
@end