#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 - 把星期一(周一)当作每个星期的开始在一年中求取周数

    先感叹一句!好长时间没有更新博客了!偶尔看到一句话,觉得被电击了 - 庸人败于懒,能人败于傲! 因此,不能再懒惰了! 今天想写一个有关计算 Week Number 的函数,刚开始觉得应该很简单,凭着感 ...

  2. 30天C#基础巩固----程序集,反射

    一:认识程序集       只要是使用VS就会和程序集打交道,我们通过编辑和生产可执行程序就会自动生成程序集.那么什么事程序集呢,.net中的dll与exe文件的都是程序集(Assembly).    ...

  3. c#中如何执行存储过程

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  4. 快速学习JavaScript面向对象编程

    到处都是属性.方法,代码极其难懂,天哪,我的程序员,你究竟在做什么?仔细看看这篇指南,让我们一起写出优雅的面向对象的JavaScript代码吧! 作为一个开发者,能否写出优雅的代码对于你的职业生涯至关 ...

  5. QT TableWidget 应用笔记

    QT TableWidget应用笔记 分类: QT2013-05-21 16:22 2561人阅读 评论(0) 收藏 举报 1.设置表头及大小 QStringList header; header&l ...

  6. oracle11g的standby性能分析报告statpack安装

    一般常见的分析standby database的性能问题的方法就是通过动态性能视图来判断,从11g开始,随着Active Data Guard功能的出现,早期的Statspack 工具可以在stand ...

  7. javascript的一些bug

    JavaScript是如今最受欢迎的编程语言之一,但受欢迎同时就是该语言自身的各种特性带来的副作用,无论该语言多美妙,每天还是有成千上万的程序员弄出一堆bug.先不要嘲笑别人,或许你也是其中之一. 给 ...

  8. 15天玩转redis —— 第四篇 哈希对象类型

    redis中的hash也是我们使用中的高频数据结构,它的构造基本上和编程语言中的HashTable,Dictionary大同小异,如果大家往后有什么逻辑需要用 Dictionary存放的话,可以根据场 ...

  9. 孙鑫MFC学习笔记11:保存图像

    1.CPtrArray指针数组 2.CPtrArray返回void指针,需要做类型转换 3.View类中的OnPaint调用OnPrepareDC和OnDraw,如果覆盖OnPaint,就不会调用On ...

  10. uums

    http://blog.csdn.net/hudon/article/details/1506042 http://www.cnblogs.com/biakia/p/4779655.html http ...