<span style="font-size:18px;">1.创建一个 一个数据模型文件(和数据库中的表类似),里面创建一些数据模型(设计属性)
创建数据模型文件 newFile-》CoreData-》Data Model 创建一个Person.xcdatamodeld文件
//给这个文件添加数据模型 Person
//通过xcode 创建Person 类
//CoreData 中的数据模型 一般要继承与NSManagedObject
//xcode --》newFile -》CoreData -》-》NSManagedObject subclass--》创建自己的模型对象
2.导入 CoreData.framework(xcode6不需要导入了)
#import <CoreData/CoreData.h>
3.
获取 本地的 xxxx.xcodemodel的模型
//有两种方式
a.//获取到coreData文件的路径,并转换成url
NSString *coreDataPath =[[NSBundle mainBundle] pathForResource:@"Person" ofType:@"momd"];
//加载coreData文件中的数据,转成model
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:coreDataPath]];
b.NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
中的nil表示连接项目中所有的 .xcodemodel 文件为一个datamodel,这是一个非常好的方法,把多个entity放在各自的xcodemodel文件中分开管理,然后用这个函数连接起来生成一个datamodel,这样就可以对应一个persistentStore。
</span><p>
</p>
@interface ViewController () <UITableViewDataSource,UITableViewDelegate>
{
//托管对象/上下文管理对象
//对数据进行增删改查
NSManagedObjectContext *_context;
//数据源数组
NSMutableArray *_dataArr;
}
- (void)initCoreData{
//从 xxx.xcdatamodeld中获取 文件关联的数据模型对象
//最终 把 文件中 所有 模型 都放入NSManagedObjectModel对象中
//1.获取关联的模型
#if 1
NSManagedObjectModel *modelFile = [NSManagedObjectModel mergedModelFromBundles:nil];
#else
//方法2:
//沙盒中会自动把工程中 .xcdatamodeld文件 变为 .momd
NSString *path = [[NSBundle mainBundle] pathForResource:@"User" ofType:@"momd"];
NSManagedObjectModel *modelFile = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
#endif
//2.设置 存储 协调器 (协调 底层和上层)
//2.1让 协调器 和 modelFile产生关联
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:modelFile];
//2.2设置数据库文件的路径
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/Mydata.sqlite"];
NSError *error = nil;
//2.3设置 存储方式 根据路径创建 数据库文件
///将coreData数据 映射到数据库
NSPersistentStore *store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:&error];
if (!store) {
//创建 失败
NSLog(@"creat store falied:%@",error.localizedDescription);
//可以抛出一个异常(程序 会 crash) 也可以不抛
[NSException raise:@"store failed:" format:@"%@",error.localizedDescription];
}
//3.托管对象 /上下文管理对象
_context = [[NSManagedObjectContext alloc] init];
//托管对象 和 协调器 产生 关联
_context.persistentStoreCoordinator = coordinator;
//_context 对数据库 进行增删改查
}
//增加
- (IBAction)addClick:(id)sender {
//把textField的内容 写入数据库
//1.放入数据模型
//不能采用 下面的写法 CoreData中的数据模型 对象属性的setter和getter方法 是没有的 需要通过NSEntityDescription 创建 对象,NSEntityDescription 中会动态 产生setter和getter方法
// UserModel *model = [[UserModel alloc] init];
// model.name = self.name.text;
//正确创建UserModel对象
//第一个参数:数据模型类的名字
//第二个参数:托管对象
//根据 数据模型 返回 一个NSEntityDescription实例对象
//这个实例对象 就是UserModel的对象
//1.给_context 操作的数据 增加一个实例对象
UserModel *model = (UserModel *)[NSEntityDescription insertNewObjectForEntityForName:@"UserModel" inManagedObjectContext:_context];
model.name = self.name.text;
model.age = @(self.age.text.intValue);
//获取首字符
model.fName = [self.name.text substringToIndex:1];
//2.插入 对象 之后保存
//回写 写入数据库文件
NSError *error = nil;
BOOL isSuccess = [_context save:&error];
if (!isSuccess) {
NSLog(@"add_error:%@",[error localizedDescription]);
}
//- save: 方法 数据库进行 增加 删除 修改 都要进行保存
}
#pragma mark - 根据名字 在数据库中 查找 数据模型对象
- (NSArray *)fetchDataWithName:(NSString *)nameStr {
//1.先设置查找请求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//2.设置 查找的数据模型对象
/*
//从_context 获取 UserModel
[NSEntityDescription entityForName:@"UserModel" inManagedObjectContext:_context];
*/
request.entity = [NSEntityDescription entityForName:@"UserModel" inManagedObjectContext:_context];
//3.设置 谓词--》匹配 要找的条件
//谓词 经常 用于 正则表达式--》来匹配数据
/*
谓词 字符串:"name like xiaohong"-->去 找指定的UserModel的对象中 找 name属性 有没有 是叫xiaohong 的 必须要完全匹配
//模糊查询
谓词 字符串:"name like *xiaohong*"-->去 找指定的UserModel的对象中 找 name属性 有没有 包含xiaohong 的字符串 必须要完全匹配
//需要
1.
NSString *str = [NSString stringWithFormat:@"*%@*",nameStr];
//2.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",str];
不能 直接这样写
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like *%@*",nameStr];
*/
if (nameStr) {
//要查询 一个对象的 匹配的属性 那么需要设置谓词
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",nameStr];
request.predicate = predicate;
}
//如果要查询 所有的数据 那么 不需要设置谓词
//执行 查询请求 返回一个数组
NSArray *resultArr = [_context executeFetchRequest:request error:nil];
return resultArr;
}
- (IBAction)deleteClick:(id)sender {
//1.根据名字 找到指定的对象
NSArray *arr = [self fetchDataWithName:self.name.text];
//2.遍历数组 一个一个删除 (如果只找到一个 那么数组就一个元素)
//用 一个 枚举的block 形式遍历
//如果要中途停止 循环 那么 *stop = YES;(类似于for 中的break)
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[_context deleteObject:obj];
}];
//最后 要注意 保存
//回写 数据库
if (![_context save:nil]) {
NSLog(@"delete:保存失败");
}
}
//更新 名字 对应的对象的 年龄
- (IBAction)updateClick:(UIButton *)sender {
//1.先找到 指定的对象
NSArray *arr = [self fetchDataWithName:self.name
.text];
//遍历 数组
for (UserModel *model in arr) {
//修改 名字
model.age = @(self.age.text.intValue);
}
//2.保存 数据
//回写到数据库文件
if (![_context save:nil]) {
NSLog(@"update:保存失败");
}
}
- (IBAction)fetchClick:(UIButton *)sender {
//查找 之后 把数据放入tableView
//1.先清空之前的数据
[_dataArr removeAllObjects];
//2.把查询 结果数组 增加到 _dataArr;
NSArray *arr = [self fetchDataWithName:self.name.text];
[_dataArr addObjectsFromArray:arr];
//刷新表格
[self.tabelView reloadData];
}
#pragma mark - tableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellName = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName];
}
UserModel *model = _dataArr[indexPath.row];
cell.textLabel.text =[NSString stringWithFormat:@"name:%@ age:%d",model.name,model.age.intValue];
return cell;
}
简单的CoreDataDemo
最新推荐文章于 2016-12-03 18:09:33 发布