#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:@"Model" 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得到请求对象
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)createUI { //创建名字label
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
nameLabel.text = @"名字";
nameLabel.font = [UIFont systemFontOfSize:];
[self.view addSubview:nameLabel]; //创建一个名字的输入框 CGRectGetMaxX得到namelLabel它的最大x坐标
_nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(nameLabel.frame), , , )];
_nameTextField.placeholder = @"请输名字";
_nameTextField.borderStyle = UITextBorderStyleBezel;
_nameTextField.tag = ;
[self.view addSubview:_nameTextField]; //创建年龄label
UILabel *ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_nameTextField.frame), , , )];
ageLabel.text = @"年龄";
ageLabel.font = [UIFont systemFontOfSize:];
[self.view addSubview:ageLabel]; //创建一个年龄的输入框
_ageTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(ageLabel.frame), , , )];
_ageTextField.placeholder = @"请输年龄";
_ageTextField.borderStyle = UITextBorderStyleBezel;
_tableView.tag = ;
[self.view addSubview:_ageTextField]; //以下创建四个button 分别对应 增 删 改 查
NSArray *titles = @[@"+",@"-",@"G",@"C"]; for (int i = ; i < titles.count; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake( + *i, , , ); [self.view addSubview:button]; [button setTitle:titles[i] forState:UIControlStateNormal];
button.tag = i + ;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; } _tableView = [[UITableView alloc] initWithFrame:CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height - ) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView]; [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"]; } - (void)buttonClicked:(UIButton *)button { int tag = (int)button.tag - ; switch (tag) {
case :
{
//增加一个数据模型对象(实体结构对象或实体对象)
/*
第一个参数:增加数据对应的模型(增加一个新的数据 根据名字取)
第二个参数:上下文对象 注:开发中可以创建多个上下文对象管理不同的数据库,一定保证对应好哪一个上下文对象
*/
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 :
{
//取点击哪个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 :
{
//获取请求对象 理解为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:];
}
//保存(写回)数据库,必须要保存数据库,否则下次进入应用没有修改
[_context save:nil];
//刷新表
[_tableView reloadData]; //遍历打印一下
for (Person *person in _dataArray) {
NSLog(@"%@",person.name);
} }
break;
case :
{
//查
//根据实体名字得到(创建)请求对象
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;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
 #import <CoreData/CoreData.h>

 //注:如果想用CoreData管理这个Person类创建出来的对象,必须继承自NSManagedObject,否则CoreData无法操作此类创建出来的对象
@interface Person : NSManagedObject @property (nonatomic,copy) NSString *name;
//在数据模型中,将简单的数据类型(int float double)转换为对象 用NSNumber
@property (nonatomic,strong) NSNumber *age; @end
 #import "Person.h"

 @implementation Person

 @synthesize age;
@synthesize name; @end

注意:做事有前提哦:

上图中的Teacher是以系统给的方式建的(不推荐)在Model里面添加的Person,开头一定要大写

结果是这个样的,UI设计可以改进

CoreData的使用的更多相关文章

  1. iOS基本数据库存储方式 - CoreData

    CoreData 创建模型文件的过程 1.选择模板 2.添加实体 3.添加实体的属性[注意]属性的首字母必须小写 一.CoreData管理类(必备以下三个类对象) 1.CoreData数据操作的上下文 ...

  2. iOS CoreData 中 objectID 的不变性

    关于 CoreData的 objectID 官方文档有这样的表述:新建的Object还没保存到持久化存储上,那么它的objectID是临时id,而保存之后,就是持久化的id,不会再变化了. 那么,我想 ...

  3. CoreData __ 基本原理

    操作过程 Context想要获取值,先要告诉连接器,我要什么东西 链接器再告诉store, 你给我什么东西, store去找 找到之后返回给链接器,链接器再返回给Context          Co ...

  4. iOS CoreData primitive accessor

    Given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstNa ...

  5. 初识CoreData与详解

    Core Data数据持久化是对SQLite的一个升级,它是iOS集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管 ...

  6. CoreData教程

    网上关于CoreData的教程能搜到不少,但很多都是点到即止,真正实用的部分都没有讲到,而基本不需要的地方又讲了太多,所以我打算根据我的使用情况写这么一篇实用教程.内容将包括:创建entity.创建r ...

  7. CoreData和SQLite多线程访问时的线程安全

    关于CoreData和SQLite多线程访问时的线程安全问题 数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常 ...

  8. IOS数据存储之CoreData使用优缺点

    前言: 学习了Sqlite数据之后认真思考了一下,对于已经习惯使用orm数据库的开发者或者对sql语句小白的开发者来说该如何做好数据库开发呢?这个上网搜了一下?看来总李多虑了!apple 提供了一种数 ...

  9. iOS开发之表视图爱上CoreData

    在接触到CoreData时,感觉就是苹果封装的一个ORM.CoreData负责在Model的实体和sqllite建立关联,数据模型的实体类就相当于Java中的JavaBean, 而CoreData的功 ...

  10. CoreData

    之前在学习使用SQLite时, 需要编写大量的sql语句,完成数据的增删改查,但对于不熟悉sql语句的开发人员来说,难度较大,调试程序比较困难. 由此出现CoreData框架,将sql的操作转换成为对 ...

随机推荐

  1. 如何解读SQL Server日志(1/3)

    SQL Server 的事务日志包含所有数据修改的操作记录.分析日志一般作为解决某些问题的最后手段,如查看某些意外的修改.理解和分析日志内容是件非常困难的事情,fn_dblog通常会输出非常多的数据, ...

  2. SpringMVC——自定义拦截器、异常处理以及父子容器配置

    自定义拦截器: 一.若想实现自定义拦截器,需要实现 org.springframework.web.servlet.HandlerInterceptor 接口. 二.HandlerIntercepto ...

  3. 类库,委托,as.is,var,泛型集合

    类库: 就是让别人调用你写的方法,并且不让别人看到你是怎么实现的.(比如说一些核心文件) 如果有功能你不会做,需要别人帮忙,那么你的同事可以帮你写好一个类,然后你来调用这个类中的方法,完成你的项目. ...

  4. Oracle导入导出命令

    //导出 exp techrpt_data/techrpt_data@orcl file=d:\_临时文件\techrpt_data.dmp owner=techrpt_data //导入 imp t ...

  5. js或css文件合并的三种方式推荐

    源文档 <http://www.jb51.net/article/32834.htm> 在Web项目的开发中,js,css文件会随着项目的开发变得越来越多,越来越大,这就给给性能方面带来一 ...

  6. vim快捷键整理(转载)

    一.移动光标 1.左移h.右移l.下移j.上移k2.向下翻页ctrl + f,向上翻页ctrl + b3.向下翻半页ctrl + d,向上翻半页ctrl + u4.移动到行尾$,移动到行首0(数字), ...

  7. 阿里社招B2B

    岗位描述:1. 按USE CASE进行业务需求分析和软件概要设计2. 进行软件详细设计和编码实现,确保性能.质量和安全3. 维护和升级现有软件产品,快速定位并修复现有软件缺陷岗位要求:1. 精通Web ...

  8. 研究base64_encode的算法

    从网上看了一些资料,为了方便自己理解,于是把它的编码原理,自己放在excel表格中清晰列出来,方便以后查阅.做的图如下:

  9. 硬盘空间满导致mysql ibd文件被删后提示Tablespace is missing for table 'db_rsk/XXX"

    昨天一早,开发人员反馈说一个测试环境报Tablespace is missing for table 'db_rsk/XXX",周末刚升级过,特地让开发回去查了下,说脚本中肯定没有drop ...

  10. 使用React并做一个简单的to-do-list

    1. 前言 说到React,我从一年之前就开始试着了解并且看了相关的入门教程,而且还买过一本<React:引领未来的用户界面开发框架 >拜读.React的轻量组件化的思想及其virtual ...