#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. SQL 聚合函数

    SQL聚合函数 MAX---最大值 MIN--最小值 AVG--平均值 SUM--求和 COUNT--记录的条数 EXample: --从MyStudent表中查询最大年龄,最小年龄,平均年龄,年龄的 ...

  3. Net.Sockets

    #region 程序集 System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // C:\Program ...

  4. 【转】同一台Windows机器中启动多个Memcached服务

    上一篇介绍了Memcached的安装,但是如果手头上只有一台机器,又想做多节点测试咋办? 这就需要在一台机器上启动多个Memcached服务了. 假设Memcached在如下目录:C:\memcach ...

  5. ASP.NET MVC系列:添加模型的验证规则

    首先,在模型类中引用 System.ComponentModel.DataAnnotations 命名空间;System.ComponentModel.DataAnnotations 命名空间提供定义 ...

  6. 重构:用Command替换条件调度程序

    注:该随笔受启发于 <重构与模式>  第七章 第7.6小节 用Command替换条件调度程序 . 对于Command不做过多解释,这里我找了两个例子.供部分园友参阅:Command例子1  ...

  7. QTableWidget详解(样式、右键菜单、表头塌陷、多选等) 2013-10-23 10:54:04

    一.设置表单样式 点击(此处)折叠或打开 table_widget->setColumnCount(4); //设置列数 table_widget->horizontalHeader()- ...

  8. iOS阶段学习第19天笔记(协议-Protocol)

    iOS学习(OC语言)知识点整理 一.关于协议(Protocol)的介绍 1)概念:协议指多个对象之间协商的一个接口对象,协议提供了一些方法用在协议的实现者和代理者      之间通讯的一种方式 2) ...

  9. Flume

    http://www.ibm.com/developerworks/cn/data/library/bd-1404flumerevolution/index.html https://flume.ap ...

  10. Oracle 数据库基础学习 (五) 多表查询

    多表查询:查询结果需要用到两个或者以上表,此时需要多表连接,产生多表查询 1.内连接(等值连接) 示例:将两个表内容连接显示 select * from dept d, emp e where d.d ...