接上篇文章,CoreData可视化创建和初始化(一)
可以自己创建一个tableView进行数据展示,并进行增删改查操作
1.需要先获取context 对象
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.context;
2.插入数据
// 增加数据
- (void)insertData{
// 数据添加
NSArray *arr = @[@{@"name":@"张三",@"age":@22,@"stuId":@6},@{@"name":@"李四",@"age":@22,@"stuId":@12},@{@"name":@"王二",@"age":@22,@"stuId":@11}];
for (NSDictionary *dict in arr) {
Model *model = [[Model alloc] initWithDictionary:dict];
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
student.name = model.name;
student.stuId = model.stuId;
student.age = model.age;
NSError *error;
[self.context save:&error];
if (error) {
NSLog(@"插入数据错误 %@",error);
}
}
}
3.查询数据
// 查询数据
- (void)fetchData{
// 查询指令
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// 获取要查询的表单
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.context];
// 给查询指令设置要查询的表单
[fetchRequest setEntity:entity];
// 自定义要查询的条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stuId > %d",3];
// 给查询指令设置查询条件
[fetchRequest setPredicate:predicate];
// 给查询进行排序 升序
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"stuId" ascending:YES];
// 年龄 升序
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
// 按照在数组的位置,越靠前优先级越高
NSArray *sortDescriptors = @[sortDescriptor1,sortDescriptor2];
// 给查询指令设置排序条件
fetchRequest.sortDescriptors = sortDescriptors;
NSError *error;
// 可以随意转化成模型
NSArray *result = [self.context executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"查询失败 %@",error);
}else{
NSMutableArray *arrM = [NSMutableArray array];
// for (NSInteger i = 0; i<result.count; i++) {
//// Student *student = result[i];
// Model *model = result[i];
// NSLog(@"%ld %@ %ld",(NSInteger)model.stuId,model.name,(NSInteger)model.age);
//// NSLog(@"%ld %@ %ld",(NSInteger)result[i].stuId,result[i].name,(NSInteger)result[i].age);
//
// }
// _modelList = arrM.copy;
for (Model *model in result) {
NSLog(@"%ld %@ %ld",(NSInteger)model.stuId,model.name,(NSInteger)model.age);
[arrM addObject:model];
}
_modelList = arrM.copy;
[self.tableView reloadData];
}
}
查询时需要主要谓词的用法
谓词查询条件:predicate
谓词的条件指令
1.比较运算符 > 、< 、== 、>= 、<= 、!= 例:@"number >= 99"
2.范围运算符:IN 、BETWEEN 例:@"number BETWEEN {1,5}" @"address IN {'shanghai','nanjing'}"
3.字符串本身:SELF 例:@"SELF == 'APPLE'"
4.字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例: @"name CONTAIN[cd] 'ang'"//包含某个字符串
@"name BEGINSWITH[c] 'sh'" //以某个字符串开头
@"name ENDSWITH[d] 'ang'" //以某个字符串结束
5.通配符:LIKE 例:@"name LIKE[cd] 'er'"//代表通配符,Like也接受[cd].
@"name LIKE[cd] '???er'"
注: 星号 "" : 代表0个或多个字符 问号 "?" : 代表一个字符
6.正则表达式:MATCHES 例:NSString regex = @"^A.+e$"; //以A开头,e结尾
@"name MATCHES %@",regex
注:[c]不区分大小写 , [d]不区分发音符号即没有重音符号, [cd]既不区分大小写,也不区分发音符号。
- 合计操作 ANY,SOME:指定下列表达式中的任意元素。比如,ANY children.age < 18。
ALL:指定下列表达式中的所有元素。比如,ALL children.age < 18。
NONE:指定下列表达式中没有的元素。比如,NONE children.age < 18。它在逻辑上等于NOT (ANY ...)。
IN:等于SQL的IN操作,左边的表达必须出现在右边指定的集合中。比如,name IN { 'Ben', 'Melissa', 'Nick' }。
提示: 1. 谓词中的匹配指令关键字通常使用大写字母
2. 谓词中可以使用格式字符串
3. 如果通过对象的key path指定匹配条件,需要使用%K
//创建查询请求实例演示
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
//查询条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@"sex = %@", @"美女"]; r
equest.predicate = pre;
// 从第几页开始显示
// 通过这个属性实现分页
//request.fetchOffset = 0;
// 每页显示多少条数据
//request.fetchLimit = 6;
//发送查询请求 NSArray *resArray = [_context executeFetchRequest:request error:nil]; [self alertViewWithMessage:@"查询所有的美女"];
4.删除数据
// 删除数据
- (void)deleteData{
// 先查找出要删除的数据然后再删除
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stuId = 11"];
request.predicate = predicate;
NSArray *result = [self.context executeFetchRequest:request error:nil];
for (Student *obj in result) {
[self.context deleteObject:obj];
}
// 如果没有save 的话,数据库并没有真的删掉数据,只是把你缓存的结果删掉了
[self.context save:nil];
// 再次查找的话,并没有从数据库里查找,重启应用程序还是有的
[self fetchData];// 查看是否删掉数据
}
5.修改数据
// 修改数据
- (void)updateData{
// 同删除数据一样,也要先查出要修改的数据,然后再进行修改
// 先查找出要删除的数据然后再删除
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stuId = 7"];
request.predicate = predicate;
NSArray *result = [self.context executeFetchRequest:request error:nil];
for (Student *obj in result) {
obj.name = @"王二";
}
// 如果没有save 的话,数据库并没有真的删掉数据,只是把你缓存的结果删掉了
[self.context save:nil];
// 再次查找的话,并没有从数据库里查找,重启应用程序还是有的
[self fetchData];// 查看是否删掉数据
}
// 调用删除和更新操作
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// [self deleteData];
[self updateData];
}
下篇文章会介绍CoreData的二次封装,在实际开发中建议使用,可移植性很好,在项目中可以快速开发。