博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
coredata使用代码实现
阅读量:4074 次
发布时间:2019-05-25

本文共 7187 字,大约阅读时间需要 23 分钟。

#import "ViewController.h"#import 
#import "UserModel.h"@interface ViewController ()
{ NSManagedObjectContext *_context;//上下文管理对象}@property (weak, nonatomic) IBOutlet UITextField *name;@property (weak, nonatomic) IBOutlet UITextField *age;@property (weak, nonatomic) IBOutlet UITableView *tableView;- (IBAction)addClick:(id)sender;- (IBAction)deleteClick:(id)sender;- (IBAction)updateClick:(id)sender;- (IBAction)fetchWithNameClick:(id)sender;- (IBAction)fetchAllClick:(id)sender;//数据源数组@property (nonatomic,strong) NSMutableArray *dataArr;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.dataArr = [[NSMutableArray alloc] init]; self.tableView.dataSource = self; self.tableView.delegate = self; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"]; //初始化 coredata [self initCoreData];}/* 使用coredata 1.创建数据模型文件-》xxx.xcdatamodeld 1.1创建 模型文件的模型 UserModel 实例 2.设计 关联 xxx.xcdatamodeld中的模型UserModel对应的数据模型类 UserModel 3.初始化CoreData 3.0 导入头文件CoreData.h 3.1从沙盒中获取 数据模型文件(在沙盒app包中数据模型文件叫做xx.momd)创建对象 NSManagedObjectModel 3.2创建 coredata 数据存储协调器(NSPersistentStoreCoordinator)关联上 数据模型文件 3.3设置 协调器的存储类型 SQLite 3.4创建 coredata上下文管理对象(NSManagedObjectContext) 4.通过上下文管理对象 对数据库进行 增删改查 *//* 有两种方式: a.//获取到coreData文件的路径,并转换成url //在包内User.xcdatamodeld会转化为 User.momd NSString *coreDataPath =[[NSBundle mainBundle] pathForResource:@"User" ofType:@"momd"]; //加载coreData文件中的数据,转成model NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:coreDataPath]]; b.NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; 中的nil表示连接项目中所有的 .xcdatamodeld 文件为一个datamodel,这是一个非常好的方法,把多个entity放在各自的xcodemodel文件中分开管理,然后用这个函数连接起来生成一个datamodel,这样就可以对应一个persistentStore。 */- (void)initCoreData { //1.创建 数据模型文件对象#if 0 //方法1 ->获取沙盒 包内资源路径 在沙盒中叫xx.momd NSURL *url = [[NSBundle mainBundle] URLForResource:@"User" withExtension:@"momd"]; NSLog(@"url:%@",url.absoluteString); NSManagedObjectModel *modelFile = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];#else NSManagedObjectModel *modelFile = [NSManagedObjectModel mergedModelFromBundles:nil];#endif //2.创建存储协调器 关联上数据模型文件 NSPersistentStoreCoordinator * coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:modelFile]; //3.设置 存储类型--> xml 、 二进制 、 sqlite //NSXMLStoreType NSBinaryStoreType NSSQLiteStoreType //成功 返回 存储对象地址 失败返回nil //url 要传 数据库文件在沙盒的路径 NSString *dataPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/myData.sqlite"]; NSError *error = nil; NSPersistentStore *store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:&error]; if (!store) { NSLog(@"设置数据库失败:%@",error.description); } //4.创建 上下文管理 _context = [[NSManagedObjectContext alloc] init]; //设置 上下文的存储协调器 _context.persistentStoreCoordinator = coordinator; //后面就可以通过上下文管理对象 对数据库进程增删改查}#pragma mark - 增删改查//增加- (IBAction)addClick:(id)sender { //UserModel *model = [[UserModel alloc] init]; //coredata 中创建 数据模型对象 需要 使用NSEntityDescription创建 ,才可以使用运行时对模型对象进行赋值 //coredata 增加模型对象 用 insertNewObjectForEntityForName: // UserModel就是数据模型类的 类名字符串 //创建 UserModel 对象 UserModel *userModel = (UserModel *)[NSEntityDescription insertNewObjectForEntityForName:@"UserModel" inManagedObjectContext:_context]; userModel.name = self.name.text; userModel.age = @(self.age.text.integerValue); userModel.fName = [self.name.text substringToIndex:1]; //保存到磁盘 //增删改 都要进行保存到磁盘 NSError *error = nil; BOOL ret = [_context save:&error]; if (!ret) {//save 失败 返回NO NSLog(@"add error:%@",error.description); }}//删除- (IBAction)deleteClick:(id)sender { //先查找 //根据名字找到 NSArray *arr = [self fetchDataWithName:self.name.text]; //遍历数组 for (UserModel *model in arr) { //删除 [_context deleteObject:model]; } //保存到磁盘 NSError *error = nil; if (![_context save:&error]) {//save 失败 返回NO NSLog(@"delete error:%@",error.description); }}- (IBAction)updateClick:(id)sender { //先查找 //根据名字找到 NSArray *arr = [self fetchDataWithName:self.name.text]; //遍历数组 for (UserModel *model in arr) { //修改 model.age = @(self.age.text.integerValue); } //保存到磁盘 NSError *error = nil; if (![_context save:&error]) { NSLog(@"update error:%@",error.description); }}#pragma mark - 根据名字进行查找- (NSArray *)fetchDataWithName:(NSString *)newName { //1.先设置 查找请求 NSFetchRequest *request = [[NSFetchRequest alloc] init]; //2.设置 查找的 实例对象 // entityForName:@"UserModel" 去 数据库 查找 UserModel request.entity = [NSEntityDescription entityForName:@"UserModel" inManagedObjectContext:_context]; //3.如果要设置 查询条件 需要设置谓词如果不设置谓词 默认 查找所有的UserModel的对象 /* 谓词语法 @"name like xiaohong" -》要查询的对象 属性中 name 属性 要完全匹配xiaohong 字符串 表示成功 -》谓词 表达式 中的 name 就是 UserModel 类中的属性名 name //如果要找匹配的age 谓词表达式应该写成 age like 12 -》name like *xiaohong* -->模糊查询 表示找到只要包含xiaohong的就成功 */ if (newName) { /* 模糊查询 NSString *str = [NSString stringWithFormat:@"name like *%@*",newName]; request.predicate = [NSPredicate predicateWithFormat:str];*/ //如果 newName有值 说明 要根据条件查询 request.predicate = [NSPredicate predicateWithFormat:@"name like %@",newName]; } //如果没有设置名字 传入nil 表示 查询所有的UserModel 对象 //设置排序准则 //排序描述器 //key 就是 对象的属性名字 //按照年龄 降序排序 NO降序 NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO]; //如果 age 就相同的可以再设置一个排序准则 按照 name排序 NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO]; //设置多个排序准则 request.sortDescriptors = @[sort,sort2]; //执行 查询请求 把结果放在数组中返回 return [_context executeFetchRequest:request error:nil];}- (IBAction)fetchWithNameClick:(id)sender { NSArray *arr = [self fetchDataWithName:self.name.text]; // [self.dataArr removeAllObjects]; //增加新数据 [self.dataArr addObjectsFromArray:arr]; //刷新表格 [self.tableView reloadData];}- (IBAction)fetchAllClick:(id)sender { NSArray *arr = [self fetchDataWithName:nil]; [self.dataArr removeAllObjects]; //增加新数据 [self.dataArr addObjectsFromArray:arr]; //刷新表格 [self.tableView reloadData];}#pragma mark - UITableView协议- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataArr.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; UserModel *model = self.dataArr[indexPath.row]; cell.textLabel.text = [NSString stringWithFormat:@"name:%@ age:%ld",model.name,model.age.integerValue]; return cell;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.name resignFirstResponder]; [self.age resignFirstResponder];}@end

转载地址:http://seyni.baihongyu.com/

你可能感兴趣的文章
mongoDB简介
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>
memcached工作原理与优化建议
查看>>
Redis与Memcached的区别
查看>>
程序员最核心的竞争力是什么?
查看>>
linux CPU个数查看
查看>>
分布式应用开发相关的面试题收集
查看>>
简单理解Socket及TCP/IP、Http、Socket的区别
查看>>
利用负载均衡优化和加速HTTP应用
查看>>
消息队列设计精要
查看>>
分布式存储系统设计(1)—— 系统架构
查看>>
MySQL数据库的高可用方案总结
查看>>
常用排序算法总结(一) 比较算法总结
查看>>
SSH原理与运用
查看>>
SIGN UP BEC2
查看>>
S3C2440中对LED驱动电路的理解
查看>>
Windows CE下USB摄像头驱动开发(以OV511为例,附带全部源代码以及讲解) [转]
查看>>
出现( linker command failed with exit code 1)错误总结
查看>>
iOS开发中一些常见的并行处理
查看>>
iOS获取手机的Mac地址
查看>>