** 使用Coredata 工程中的DataModel创建:系统创建、手动创建**
** 使用Coredata需要要导入<CoreData/CoreData.h> **
1、系统创建(系统创建生成NSPersistentContainer, iOS10+,iPhoneX;iOS8+ 使用手动创建Coredata)
1.1创建工程
1.2 创建实体对象
1.3 实体对象命名,Language属性值选择
1.4 实体对象属性codegen选择
1.5 添加实体对象属性
1.6 创建实体对象的子类文件
1.7 创建NSManagedObject模型(模型命名不可和实体名称相同)
1.8为模型添加属性
1.9 Viewcontroller.m (由于系统创建datamodel,系统已将coredata数据库初始化,无需自己初始化数据库)
1 // 2 // ViewController.m 3 // Coredatanpp 4 // 5 // Created by Z_小圣 on 2019/3/19. 6 // Copyright © 2019年 奶瓶瓶. All rights reserved. 7 // 8 9 #import "ViewController.h"10 #import "BabyModal.h"11 #import "AppDelegate.h"12 @interface ViewController ()13 {14 NSManagedObjectContext *_context;15 NSPersistentContainer *_container;16 NSManagedObjectModel *_managedObjectModel;17 }18 @end19 20 @implementation ViewController21 22 - (void)viewDidLoad {23 [super viewDidLoad];24 AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;25 _container = appDelegate.persistentContainer;26 //返回沙盒中存储数据库的文件夹URL路径,这是一个静态方法,表示数据库的文件路径是唯一的27 NSURL * url = [NSPersistentContainer defaultDirectoryURL];28 NSLog(@"沙盒路径%@",url);29 _context = _container.viewContext;30 _managedObjectModel = _container.managedObjectModel;31 // Do any additional setup after loading the view, typically from a nib.32 }33 //添加方法34 - (IBAction)addAction:(UIButton *)sender {35 // 1.创建一个新的继承于NSManagedObject的子类BabyModal36 BabyModal *baby = [NSEntityDescription insertNewObjectForEntityForName:@"Baby" inManagedObjectContext:_context];37 38 //2.根据表Baby中的键值,给NSManagedObject对象赋值39 baby.name = [NSString stringWithFormat:@"长江-%d",arc4random()%100];40 baby.age = arc4random()%20;41 baby.gender = arc4random()%2 == 0 ? 0: 1;42 43 // 3.保存插入的数据44 NSError *error = nil;45 if ([_context save:&error]) {46 NSLog(@"数据插入到数据库成功");47 }else{48 NSLog(@"数据插入到数据库失败,%@",error);49 }50 51 }52 //查询方法53 - (IBAction)queryAction:(UIButton *)sender {54 55 //创建查询请求56 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Baby"];57 //查询条件58 NSPredicate *pre = [NSPredicate predicateWithFormat:@"gender = %@", @"0"];59 request.predicate = pre;60 // 从第几页开始显示61 // 通过这个属性实现分页62 //request.fetchOffset = 0;63 // 每页显示多少条数据64 //request.fetchLimit = 6;65 //发送查询请求66 NSArray *resArray = [_context executeFetchRequest:request error:nil];67 //打印查询数据68 for (BabyModal *modal in resArray ) {69 NSLog(@"查询结果:姓名=%@ ,年龄=%ld ,性别=%@",modal.name,modal.age,[NSString stringWithFormat:@"%d",modal.gender]);70 }71 }72 //删除方法73 - (IBAction)deleteAction:(UIButton *)sender {74 //创建删除请求75 NSFetchRequest *deleRequest = [NSFetchRequest fetchRequestWithEntityName:@"Baby"];76 //删除条件77 NSPredicate *pre = [NSPredicate predicateWithFormat:@"age < %d", 10];78 deleRequest.predicate = pre;79 //返回需要删除的对象数组80 NSArray *deleArray = [_context executeFetchRequest:deleRequest error:nil];81 //从数据库中删除82 for (BabyModal *stu in deleArray) {83 [_context deleteObject:stu];84 }85 NSError *error = nil;86 //保存--记住保存87 if ([_context save:&error]) {88 NSLog(@"删除 age < 10 的数据");89 }else{90 NSLog(@"删除数据失败, %@", error);91 }92 }93 94 95 96 @end
2.手动创建(iOS8+ 推荐使用)
2.1 创建工程
2.2 创建DataModel
2.3 创建实体对象
2.4 实体对象命名,Language属性值选择
2.5 实体对象属性codegen选择
2.6 添加实体对象属性
2.7 创建实体对象的子类文件
2.8 创建NSManagedObject模型 (模型命名不可和实体名称相同)
2.9 为模型添加属性
2.10 ViewController.m (URLForResource参数需要根据创建的Datamodel的名称来)
1 // 2 // ViewController.m 3 // Coredatanpp 4 // 5 // Created by Z_小圣 on 2019/3/19. 6 // Copyright © 2019年 奶瓶瓶. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "BabyModal.h" 11 @interface ViewController () 12 { 13 NSManagedObjectContext *_context; 14 } 15 @end 16 17 @implementation ViewController 18 19 - (void)viewDidLoad { 20 [super viewDidLoad]; 21 [self createSqlite];//创建数据库 22 // Do any additional setup after loading the view, typically from a nib. 23 } 24 //创建数据库 25 - (void)createSqlite{ 26 27 //1、创建模型对象 28 //获取模型路径 URLForResource参数需要根据创建的Datamodel的名称来 29 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoredatanppManual" withExtension:@"momd"]; 30 //根据模型文件创建模型对象 31 NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 32 33 //2、创建持久化存储助理:数据库 34 //利用模型对象创建助理对象 35 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; 36 37 //数据库的名称和路径 38 NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 39 NSString *sqlPath = [docStr stringByAppendingPathComponent:@"coreData.sqlite"]; 40 NSLog(@"数据库 path = %@", sqlPath); 41 NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath]; 42 43 NSError *error = nil; 44 //设置数据库相关信息 添加一个持久化存储库并设置类型和路径,NSSQLiteStoreType:SQLite作为存储库 45 [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:&error]; 46 47 if (error) { 48 NSLog(@"添加数据库失败:%@",error); 49 } else { 50 NSLog(@"添加数据库成功"); 51 } 52 53 //3、创建上下文 保存信息 对数据库进行操作 54 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 55 56 //关联持久化助理 57 context.persistentStoreCoordinator = store; 58 _context = context; 59 } 60 //添加方法 61 - (IBAction)addAction:(UIButton *)sender { 62 // 1.创建一个新的继承于NSManagedObject的子类BabyModal 63 BabyModal *baby = [NSEntityDescription insertNewObjectForEntityForName:@"Baby" inManagedObjectContext:_context]; 64 65 //2.根据表Baby中的键值,给NSManagedObject对象赋值 66 baby.name = [NSString stringWithFormat:@"长江-%d",arc4random()%100]; 67 baby.age = arc4random()%20; 68 baby.gender = arc4random()%2 == 0 ? 0: 1; 69 70 // 3.保存插入的数据 71 NSError *error = nil; 72 if ([_context save:&error]) { 73 NSLog(@"数据插入到数据库成功"); 74 }else{ 75 NSLog(@"数据插入到数据库失败,%@",error); 76 } 77 78 } 79 //查询方法 80 - (IBAction)queryAction:(UIButton *)sender { 81 82 //创建查询请求 83 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Baby"]; 84 //查询条件 85 NSPredicate *pre = [NSPredicate predicateWithFormat:@"gender = %@", @"0"]; 86 request.predicate = pre; 87 // 从第几页开始显示 88 // 通过这个属性实现分页 89 //request.fetchOffset = 0; 90 // 每页显示多少条数据 91 //request.fetchLimit = 6; 92 //发送查询请求 93 NSArray *resArray = [_context executeFetchRequest:request error:nil]; 94 //打印查询数据 95 for (BabyModal *modal in resArray ) { 96 NSLog(@"查询结果:姓名=%@ ,年龄=%ld ,性别=%@",modal.name,modal.age,[NSString stringWithFormat:@"%d",modal.gender]); 97 } 98 } 99 //删除方法100 - (IBAction)deleteAction:(UIButton *)sender {101 //创建删除请求102 NSFetchRequest *deleRequest = [NSFetchRequest fetchRequestWithEntityName:@"Baby"];103 //删除条件104 NSPredicate *pre = [NSPredicate predicateWithFormat:@"age < %d", 10];105 deleRequest.predicate = pre;106 //返回需要删除的对象数组107 NSArray *deleArray = [_context executeFetchRequest:deleRequest error:nil];108 //从数据库中删除109 for (BabyModal *stu in deleArray) {110 [_context deleteObject:stu];111 }112 NSError *error = nil;113 //保存--记住保存114 if ([_context save:&error]) {115 NSLog(@"删除 age < 10 的数据");116 }else{117 NSLog(@"删除数据失败, %@", error);118 }119 }120 121 122 123 @end
3.实施中遇到问题
3.1错误信息:
:-1: Multiple commands produce '/Users/z_xiaosheng/Library/Developer/Xcode/DerivedData/TeacherCoredata-gmqlwsropogypygztobrkbxffcqs/Build/Intermediates.noindex/TeacherCoredata.build/Debug-iphonesimulator/TeacherCoredata.build/Objects-normal/x86_64/Coreteacheppp+CoreDataProperties.o':1) Target 'TeacherCoredata' (project 'TeacherCoredata') has compile command with input '/Users/z_xiaosheng/Desktop/test/TeacherCoredata/Coreteacheppp+CoreDataProperties.m'2) Target 'TeacherCoredata' (project 'TeacherCoredata') has compile command with input '/Users/z_xiaosheng/Library/Developer/Xcode/DerivedData/TeacherCoredata-gmqlwsropogypygztobrkbxffcqs/Build/Intermediates.noindex/TeacherCoredata.build/Debug-iphonesimulator/TeacherCoredata.build/DerivedSources/CoreDataGenerated/TeacherCoredata/Coreteacheppp+CoreDataProperties.m'
错误原因:实体属性Codegen(编译,生成)值为非Manual/None,创建出来的类编译后会报错。
解决方案:选中实体将实体属性Codegen(编译,生成)值改为Manual/None,清空当前build,重新编译