本篇来介绍一下Core Data的增删改查.
增
这里,增就直接使用AppDelegate里头生成的persistentContainer的viewContext了.以及saveContext方法.
1.取出NSManagedObjectContext.
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.persistentContainer.viewContext;
2.通过上下文,新建一个CoreData Entity模型.
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:context];
3.进行属性设置
employee.name = @"张立强";
employee.age = 48;
employee.sex = @"女";
4.保存上下文
[delegate saveContext];
如果不保存上下文的话.那么存储就是失效的
查
为何先说查,毕竟查出来了才好删嘛(PS.直接删除数据库文件的当我没说哈).
/// 2.查
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
/// 查询条件
// fetchRequest.predicate = [NSPredicate predicateWithFormat:@"age = 30"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name == '张立强1'"];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]];
NSArray <Employee *> *array = [context executeFetchRequest:fetchRequest error:nil];
for (Employee *employee in array) {
NSLog(@"employee age : %hd" ,employee.age);
}
改
一般要改点什么,都是先查出来再改.改的话,走一遍增的后半部分逻辑就行.(千万别忘了保存)
/// ------比如我已经查出来employee了
employee.name = @"abc";
employee.age = 12;
[delegate saveContext];
删
我们就在查的基础上讲删吧.
for (Employee *employee in array) {
NSLog(@"employee age : %hd" ,employee.age);
[context deleteObject:employee];
}
[delegate saveContext];
使用context的 deleteObject:方法可以轻松的删除一个实体对象.
最后,别忘了保存改动.