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:@"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的使用的更多相关文章
- iOS基本数据库存储方式 - CoreData
CoreData 创建模型文件的过程 1.选择模板 2.添加实体 3.添加实体的属性[注意]属性的首字母必须小写 一.CoreData管理类(必备以下三个类对象) 1.CoreData数据操作的上下文 ...
- iOS CoreData 中 objectID 的不变性
关于 CoreData的 objectID 官方文档有这样的表述:新建的Object还没保存到持久化存储上,那么它的objectID是临时id,而保存之后,就是持久化的id,不会再变化了. 那么,我想 ...
- CoreData __ 基本原理
操作过程 Context想要获取值,先要告诉连接器,我要什么东西 链接器再告诉store, 你给我什么东西, store去找 找到之后返回给链接器,链接器再返回给Context Co ...
- iOS CoreData primitive accessor
Given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstNa ...
- 初识CoreData与详解
Core Data数据持久化是对SQLite的一个升级,它是iOS集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管 ...
- CoreData教程
网上关于CoreData的教程能搜到不少,但很多都是点到即止,真正实用的部分都没有讲到,而基本不需要的地方又讲了太多,所以我打算根据我的使用情况写这么一篇实用教程.内容将包括:创建entity.创建r ...
- CoreData和SQLite多线程访问时的线程安全
关于CoreData和SQLite多线程访问时的线程安全问题 数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常 ...
- IOS数据存储之CoreData使用优缺点
前言: 学习了Sqlite数据之后认真思考了一下,对于已经习惯使用orm数据库的开发者或者对sql语句小白的开发者来说该如何做好数据库开发呢?这个上网搜了一下?看来总李多虑了!apple 提供了一种数 ...
- iOS开发之表视图爱上CoreData
在接触到CoreData时,感觉就是苹果封装的一个ORM.CoreData负责在Model的实体和sqllite建立关联,数据模型的实体类就相当于Java中的JavaBean, 而CoreData的功 ...
- CoreData
之前在学习使用SQLite时, 需要编写大量的sql语句,完成数据的增删改查,但对于不熟悉sql语句的开发人员来说,难度较大,调试程序比较困难. 由此出现CoreData框架,将sql的操作转换成为对 ...
随机推荐
- Sql去重语句
海量数据(百万以上),其中有些全部字段都相同,有些部分字段相同,怎样高效去除重复? 如果要删除手机(mobilePhone),电话(officePhone),邮件(email)同时都相同的数据,以前一 ...
- jQuery使用经验建议
在开发过很多 jQuery 插件以后,我慢慢的摸索出了一套开发jQuery插件比较标准的结构和模式.这样我就可以复制并粘贴大部分的代码结构,只要专注最主要的逻辑代码就行了. 使用相同的设计模式和架构也 ...
- Java连接MYSQL 数据库的连接步骤
这篇文章主要以MySQL为例讲下Java如何连接到数据库的. 当然,首先要安装有JDK(一般是JDK1.5.X).然后安装MySQL,这些都比较简单,具体过程就不说了.配置好这两个环境后,下载JDBC ...
- How do you install mysql-connector-python (development version) through pip?
12down votefavorite 8 http://stackoverflow.com/questions/31748278/how-do-you-install-mysql-connector ...
- DokuWiki用storage的模式在sae上部署后速度太慢
利用sae做的io wrapper接口,对dokuwiki做了基于sae的分布式storage存储改造,能正常安装和运行,但速度太慢,基本没什么用. 定义一个常量: define('SAESTORE_ ...
- java必看书籍
Java核心技术 卷1 基础知识(第9版)Java核心技术 卷II 高级特性(第9版) 数据库系统概念(原书第6版)Oracle 从入门到精通MySQL数据库应用从入门到精通 Java并发编程实战(第 ...
- 高效 Java Web 开发框架 JessMA v3.2.3 正式发布
JessMA(原名:Portal-Basic)是一套功能完备的高性能 Full-Stack Web 应用开发框架,内置可扩展的 MVC Web 基础架构和 DAO 数据库访问组件(内部已提供了 Hib ...
- 【转】PHP计划任务:如何使用Linux的Crontab执行PHP脚本
转:https://www.centos.bz/2011/03/auto-run-task-crontab/ 我们的PHP程序有时候需要定时执行,我们可以使用ignore_user_abort函数或是 ...
- 【GOF23设计模式】观察者模式
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_观察者模式.广播机制.消息订阅.网络游戏对战原理 package com.test.observer; import ja ...
- Linux 学习手记(6): 磁盘、分区、MBR与GPT
1. 磁盘在LINUX中的表示 Linux所有设备都被抽象为一个文件,保存在/dev目录下 设备名称一般为hd[a-z]或者sd[a-z]([a-z]为分区号),如:hda.hdb.sda.sdb I ...