** 使用Coredata 工程中的DataModel建立:系統建立、手動建立**sql
** 使用Coredata須要要導入<CoreData/CoreData.h> **數據庫
一、系統建立(系統建立生成NSPersistentContainer, iOS10+,iPhoneX;iOS8+ 使用手動建立Coredata)數組
1.1建立工程app
1.2 建立實體對象dom
1.3 實體對象命名,Language屬性值選擇iphone
1.4 實體對象屬性codegen選擇fetch
1.5 添加實體對象屬性ui
1.6 建立實體對象的子類文件url
1.7 建立NSManagedObject模型(模型命名不可和實體名稱相同)spa
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 @end 19 20 @implementation ViewController 21 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的子類BabyModal 36 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 //一、建立模型對象 28 //獲取模型路徑 URLForResource參數須要根據建立的Datamodel的名稱來 29 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoredatanppManual" withExtension:@"momd"]; 30 //根據模型文件建立模型對象 31 NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 32 33 //二、建立持久化存儲助理:數據庫 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 //三、建立上下文 保存信息 對數據庫進行操做 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,從新編譯