#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. Moon.Orm 5.0 (MQL版) 驱动开发方案

    Moon.Orm 5.0 (MQL版) 配置说明 这一文中说明了如何配置,如何写自己的驱动.要写自己的驱动方法就是继承基类Db, Db的类结构,点击查看

  2. C++二维码相关库编译

    一.瞎想 坐在地铁上闲来无聊,突然想到了二维码,顺手就百度了下相关的资料,目前C++二维码相关的库不多,也就zbar(开源中国上下了半天也没下载下来).zxing,不过这两个库据说都是解析二维码的,不 ...

  3. ROS 不能再详细的安装教程

    版权声明:本文为博主原创文章,转载请标明出处: http://www.cnblogs.com/liu-fa/p/5779206.html 关于ROS(Robot OS 机器人操作系统),估计看这个博文 ...

  4. php对xml文件进行CURD操作

    XML是一种数据存储.交换.表达的标准: - 存储:优势在于半结构化,可以自定义schema,相比关系型二维表,不用遵循第一范式(可以有嵌套关系): - 交换:可以通过schema实现异构数据集成: ...

  5. MySQL 5.1 参考手册CHM (官方 简体中文版)

    点此下载: MySQL 5.1 参考手册CHM (官方 简体中文版) 在线文档:http://doc.mysql.cn/mysql5/refman-5.1-zh.html-chapter/

  6. 基于MVC4+EasyUI的Web开发框架经验总结(3)- 使用Json实体类构建菜单数据

    最近花了不少时间在重构和进一步提炼我的Web开发框架上,力求在用户体验和界面设计方面,和Winform开发框架保持一致,而在Web上,我主要采用EasyUI的前端界面处理技术,走MVC的技术路线,在重 ...

  7. android app自动化测试之UIAutomator

    一.UIAutomator Android自动化测试工具有很多,但是要免费.易上手,本人觉得就直接使用Eclipse自带的UIAutomator就不错.测试人员无需跟开发要代码信息,只要手机上有安装之 ...

  8. PHPUnit单元测试中类protected/private方法测试

    这里首先有一个问题要考虑的是,这类方法是否要被测试? 理论上,这类方法都会被其它public类型的方法调用,只要对那些public的方法做充分的测试,就可以保证这些方法的可靠性,就没有必要再测了.好像 ...

  9. pageEncoding的默认设置

    windows-->preference-->myeclipse-->files and editors-->jsp 右侧 Encoding 选择  ISO 10646/Uni ...

  10. poj-1611-The Suspects

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 34284   Accepted: 16642 De ...