iOS CoreData 開發,ioscoredata開發
新年新氣象,曾經的妹子結婚了,而光棍的我決定書寫部落格~ 廢話結束。
本人不愛使用第三方的東東,喜歡原汁原味的官方版本,本次帶來CoreData資料存放區篇~
建立應用
勾上Use Core Data,不勾也行,後面再添加上去一樣的
點擊coredata檔案,look下
添加實體,點擊下面的Add Entity即可,或者通過菜單操作,效果一樣。
建立一個實體類
接著,產生代碼:
點擊Create NSManagedObject Subclass ....,然後選擇我們的User,產生代碼
寫代碼之前,先來點介紹吧,主要涉及到下面三個東東
1、Managed Object Model , 理解成資料庫吧,儲存了Entity,就是你要儲存的東西
2、Persistent Store Coordinate, 理解成資料庫連接吧,裡面存放了資料存放區到具體的檔案等等資訊
3、Managed Object Context, 資料內容,基本上所有的操作都是通過這個的。
下面進入寫代碼狀態:
上面三個對象,一個不可少,所以,先來初始化之類的操作吧
1 ///定義三個屬性2 3 4 @property(strong,nonatomic) NSManagedObjectModel *cdModel;5 @property(strong,nonatomic) NSManagedObjectContext *cdContext;6 @property(strong,nonatomic) NSPersistentStoreCoordinator *cdCoordinator;
1 - (NSManagedObjectModel *)cdModel 2 { 3 if(!_cdModel) 4 { 5 _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil]; 6 } 7 8 return _cdModel; 9 }10 11 - (NSPersistentStoreCoordinator *)cdCoordinator12 {13 if(!_cdCoordinator)14 {15 //find the database16 NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:DBNAME];17 NSURL *dbPath = [NSURL fileURLWithPath:dirPath];18 NSError *err;19 _cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.cdModel];20 if(![_cdCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbPath options:nil error:&err])21 {22 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);23 }24 dirPath = nil;25 dbPath = nil;26 }27 return _cdCoordinator;28 }29 30 - (NSManagedObjectContext *)cdContext31 {32 if(!_cdContext)33 {34 _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];35 [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];36 }37 return _cdContext;38 }
下面進行CRUD操作
1 - (void)insertToDB:(NSString *)username password:(NSString *)password 2 { 3 User *u = (User *)[NSEntityDescription insertNewObjectForEntityForName:TBNAME inManagedObjectContext:self.cdContext]; 4 u.username = username; 5 u.password = password; 6 NSError *err; 7 if(![self.cdContext save:&err]) 8 { 9 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);10 }11 }12 13 - (void)readFromDb14 {15 NSFetchRequest *fetch = [[NSFetchRequest alloc] init];16 NSEntityDescription *entity = [NSEntityDescription entityForName:TBNAME inManagedObjectContext:self.cdContext];17 [fetch setEntity:entity];18 NSError* err;19 NSArray *results = [self.cdContext executeFetchRequest:fetch error:&err];20 if(err)21 {22 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);23 return;24 }25 [results enumerateObjectsUsingBlock:^(User *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {26 NSLog(@"----%@ %@",user.username,user.password);27 }];28 }
好的,來測試下:
算了,時間來不及了,要睡覺了,就不囉嗦了,下面是完整代碼
1 // 2 // ViewController.m 3 // CoreDataTest 4 // 5 // Created by winter on 16/2/14. 6 // Copyright © 2016年 winter. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import <CoreData/CoreData.h> 11 #import "User.h" 12 13 /// define database name 14 #define DBNAME @"CoreDataTest.sqlite" 15 /// define entity 16 #define TBNAME @"User" 17 18 19 @interface ViewController () 20 { 21 22 } 23 ///定義三個屬性 24 25 26 @property(strong,nonatomic) NSManagedObjectModel *cdModel; 27 @property(strong,nonatomic) NSManagedObjectContext *cdContext; 28 @property(strong,nonatomic) NSPersistentStoreCoordinator *cdCoordinator; 29 30 31 @end 32 33 @implementation ViewController 34 35 #pragma mark - 實現三個屬性的getter Method 36 37 - (NSManagedObjectModel *)cdModel 38 { 39 if(!_cdModel) 40 { 41 _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil]; 42 } 43 44 return _cdModel; 45 } 46 47 - (NSPersistentStoreCoordinator *)cdCoordinator 48 { 49 if(!_cdCoordinator) 50 { 51 //find the database 52 NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:DBNAME]; 53 NSURL *dbPath = [NSURL fileURLWithPath:dirPath]; 54 NSError *err; 55 _cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.cdModel]; 56 if(![_cdCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbPath options:nil error:&err]) 57 { 58 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason); 59 } 60 dirPath = nil; 61 dbPath = nil; 62 } 63 return _cdCoordinator; 64 } 65 66 - (NSManagedObjectContext *)cdContext 67 { 68 if(!_cdContext) 69 { 70 _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 71 [_cdContext setPersistentStoreCoordinator:self.cdCoordinator]; 72 } 73 return _cdContext; 74 } 75 76 77 #pragma mark - crud 78 - (void)insertToDB:(NSString *)username password:(NSString *)password 79 { 80 User *u = (User *)[NSEntityDescription insertNewObjectForEntityForName:TBNAME inManagedObjectContext:self.cdContext]; 81 u.username = username; 82 u.password = password; 83 NSError *err; 84 if(![self.cdContext save:&err]) 85 { 86 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason); 87 } 88 } 89 90 - (void)readFromDb 91 { 92 NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; 93 NSEntityDescription *entity = [NSEntityDescription entityForName:TBNAME inManagedObjectContext:self.cdContext]; 94 [fetch setEntity:entity]; 95 NSError* err; 96 NSArray *results = [self.cdContext executeFetchRequest:fetch error:&err]; 97 if(err) 98 { 99 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);100 return;101 }102 [results enumerateObjectsUsingBlock:^(User *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {103 NSLog(@"----%@ %@",user.username,user.password);104 }];105 }106 107 108 - (void)viewDidLoad {109 [super viewDidLoad];110 // Do any additional setup after loading the view, typically from a nib.111 [self insertToDB:@"wang" password:@"password"];112 113 }114 115 - (void)viewDidAppear:(BOOL)animated116 {117 [super viewDidAppear:animated];118 [self readFromDb];119 }120 121 - (void)didReceiveMemoryWarning {122 [super didReceiveMemoryWarning];123 // Dispose of any resources that can be recreated.124 }125 126 @end