建立數據庫android
新建文件,選擇CoreData
-> DataModel
ios
添加實體(表),Add Entity
sql
給表中添加屬性,點擊Attributes
下方的‘+’號數據庫
建立模型文件fetch
新建文件,選擇CoreData
-> NSManaged Object subclass
spa
根據提示,選擇實體code
經過代碼,關聯數據庫和實體orm
- (void)viewDidLoad { [super viewDidLoad]; /* * 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 設置CoreData數據庫的名字和路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; _context = context; }
添加元素 - Createsqlite
-(IBAction)addEmployee{ // 建立一個員工對象 //Employee *emp = [[Employee alloc] init]; 不能用此方法建立 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; emp.name = @"wangwu"; emp.height = @1.80; emp.birthday = [NSDate date]; // 直接保存數據庫 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
讀取數據 - Read對象
-(IBAction)readEmployee{ // 1.FetchRequest 獲取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 3.設置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 4.執行請求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //NSLog(@"%@",emps); //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
修改數據 - Update
-(IBAction)updateEmployee{ // 改變zhangsan的身高爲2m // 1.查找到zhangsan // 1.1FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 1.3執行請求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.更新身高 for (Employee *e in emps) { e.height = @2.0; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
刪除數據 - Delete
-(IBAction)deleteEmployee{ // 刪除 lisi // 1.查找lisi // 1.1FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"lisi"]; request.predicate = pre; // 1.3執行請求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.刪除 for (Employee *e in emps) { [_context deleteObject:e]; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
建立數據庫
新建文件,選擇CoreData
-> DataModel
添加實體(表),Add Entity
, 注意:這裏根據關聯添加多個實體
給表中添加屬性,點擊Attributes
下方的‘+’號
建立模型文件
新建文件,選擇CoreData
-> NSManaged Object subclass
根據提示,選擇實體,注意:這裏先選擇被關聯的實體,最後添加最上層的實體
經過代碼,關聯數據庫和實體
- (void)viewDidLoad { [super viewDidLoad]; /* * 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 設置CoreData數據庫的名字和路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; _context = context; }
添加元素 - Create
-(IBAction)addEmployee{ // 1. 建立兩個部門 ios android //1.1 iOS部門 Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; iosDepart.name = @"ios"; iosDepart.departNo = @"0001"; iosDepart.createDate = [NSDate date]; //1.2 Android部門 Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; andrDepart.name = @"android"; andrDepart.departNo = @"0002"; andrDepart.createDate = [NSDate date]; //2. 建立兩個員工對象 zhangsan屬於ios部門 lisi屬於android部門 //2.1 zhangsan Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; zhangsan.name = @"zhangsan"; zhangsan.height = @(1.90); zhangsan.birthday = [NSDate date]; zhangsan.depart = iosDepart; //2.2 lisi Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; lisi.name = @"lisi"; lisi.height = @2.0; lisi.birthday = [NSDate date]; lisi.depart = andrDepart; //3. 保存數據庫 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
讀取信息 - Read
-(IBAction)readEmployee{ // 讀取ios部門的員工 // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置過濾條件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"]; request.predicate = pre; // 4.執行請求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 部門 %@",emp.name,emp.depart.name); } }
其餘功能與前幾種相似,這裏不在贅述
準備工做和上面相似,主要是查詢方式不一樣
模糊查詢
-(IBAction)readEmployee{ // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置排序 // 按照身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3.模糊查詢 // 3.1 名字以"wang"開頭// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];// request.predicate = pre; // 名字以"1"結尾// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];// request.predicate = pre; // 名字包含"wu1"// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];// request.predicate = pre; // like 匹配 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"]; request.predicate = pre; // 4.執行請求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
分頁查詢
-(void)pageSeacher{ // 1. FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2. 設置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3. 分頁查詢 // 總有共有15數據 // 每次獲取6條數據 // 第一頁 0,6 // 第二頁 6,6 // 第三頁 12,6 3條數據 // 3.1 分頁的起始索引 request.fetchOffset = 12; // 3.2 分頁的條數 request.fetchLimit = 6; // 4. 執行請求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } // 5. 遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
注意:
建立多個數據庫,即建立多個
DataModel
一個數據庫對應一個上下文
須要根據bundle名建立上下文
添加或讀取信息,須要根據不一樣的上下文,訪問不一樣的實體
關聯數據庫和實體
- (void)viewDidLoad { [super viewDidLoad]; // 一個數據庫對應一個上下文 _companyContext = [self setupContextWithModelName:@"Company"]; _weiboContext = [self setupContextWithModelName:@"Weibo"]; } /** * 根據模型文件,返回一個上下文 */-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 // 注意:若是使用下面的方法,若是 bundles爲nil 會把bundles裏面的全部模型文件的表放在一個數據庫 //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 改成如下的方法獲取: NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 告訴Coredata數據庫的名字和路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName]; NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; // 3. 返回上下文 return context; }
添加元素
-(IBAction)addEmployee{ // 1. 添加員工 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext]; emp.name = @"zhagsan"; emp.height = @2.3; emp.birthday = [NSDate date]; // 直接保存數據庫 [_companyContext save:nil]; // 2. 發微博 Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext]; status.text = @"發了一條微博!"; status.createDate = [NSDate date]; [_weiboContext save:nil]; }