数据库操作需要几个基本要素:
- CoreData支持,(默认模版选择比较关键,因为有一些AppDelegate配置)
- editor自动创建的 db名+CoreDataClass 和 db名+CoreDataProperties
- AppDelegate 对象, 通过
(AppDelegate*)[UIApplication sharedApplication].delegate;
获得 - 数据库链接的context 通过
appDelegate.persistentContainer.viewContext
获得
然后就可以愉快的操作了:
添加对象
Dog *dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
static NSInteger index = 0;
dog.name = [NSString stringWithFormat:@"tom%ld",index++];
dog.sex = @"公";
dog.age = [NSString stringWithFormat:@"%uyears",arc4random() % 15];
[_app saveContext];
注意的是数据库不支持自动计数,所以需要自己去处理,或者按照搜索排序
另外注意一点,添加可以对同一个内容添加多次,所以自己做好检测
搜索
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest :request error:nil];
for (Dog *dog in array) {
NSLog(@"dog name:%@",dog.name);
}
如果想获得所有数值则把
request.predicate
条件清除
删除
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog *dog in array) {
[_app.persistentContainer.viewContext deleteObject:dog];
}
NSLog(@"DELETE SUCCESS!!");
[_app saveContext];
} else
NSLog(@"NOT FOUND DATA");
原理就是对搜索的结果进行操作处理
更新
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog *dog in array) {
dog.name = @"jerry8";
}
[_app saveContext];
NSLog(@"UPDATA SUCCESS!!");
} else
NSLog(@"NOT FOUND DATA");
都是对搜索操作的扩展
参考:
https://www.jianshu.com/p/f3a032f97c6c
多条件查询
https://blog.csdn.net/qq_29892943/article/details/52765344