NSMangedObject 是Model的一行數據android
// // ViewController.m // CoreData // // Created by ling on 15/12/29. // Copyright © 2015年 ling. All rights reserved. // #import "ViewController.h" #import <CoreData/CoreData.h> #import "Person.h" @interface ViewController () @property (nonatomic, strong)NSManagedObjectContext *context; @property (weak, nonatomic) IBOutlet UITextField *name; @property (weak, nonatomic) IBOutlet UITextField *age; @property (weak, nonatomic) IBOutlet UITextField *height; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //1.建立模型文件 【一個數據庫裏的表】 //2.添加實體 【一張表】 //3.建立實體類 【數據模型model】 //4.生成上下文 關聯模型文件生成數據庫 // 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; //上下文關聯數據庫 //model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; //持久化存儲調度器.持久化是把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //告訴數據庫的名字和路徑 [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"Company.sqlite"]] options:nil error:nil]; NSLog(@"%@",[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"Company.sqlite"]); context.persistentStoreCoordinator = store; _context = context; } #pragma mark - CURD - (IBAction)addPerson:(UIButton *)sender { //建立一個員工對象 Person *p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context]; p.name = self.name.text; p.age = [NSNumber numberWithInt:self.age.text.intValue]; p.height = [NSNumber numberWithDouble:self.height.text.doubleValue]; //直接保存到數據庫 [_context save:nil]; } - (IBAction)alertPerson:(UIButton *)sender { } - (IBAction)readPerson:(UIButton *)sender { //1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //2.設置過濾條件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"time"]; //request.predicate = pre; //3.設置排序 ascending升序 NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heightSort]; //4.執行請求 NSArray *ps = [_context executeFetchRequest:request error:nil]; Person *p = ps.firstObject; NSLog(@"ps:%@",p.name); } - (IBAction)updatePerson:(UIButton *)sender { //1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //2.設置過濾條件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"time"]; request.predicate = pre; //3.執行請求 NSArray *ps = [_context executeFetchRequest:request error:nil]; for (Person *p in ps) { p.height = @2.0; } //4.保存 [_context save:nil]; } - (IBAction)deletePerson:(UIButton *)sender { //1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //2.設置過濾條件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"time"]; request.predicate = pre; //3.執行請求 NSArray *ps = [_context executeFetchRequest:request error:nil]; for (Person *p in ps) { [_context deleteObject:p]; } //4.保存 [_context save:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
建立多一張部門Department表,人是在部門裏面的,因此人的destination目的地創建關係relationshipios
#pragma mark 添加員工 -(IBAction)addEmployee{ // 建立兩個部門 ios android Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; iosDepart.name = @"ios"; iosDepart.departNo = @"0001"; iosDepart.createDate = [NSDate date]; Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; andrDepart.name = @"android"; andrDepart.departNo = @"0002"; andrDepart.createDate = [NSDate date]; // 建立兩個員工對象 zhangsan屬於ios部門 lisi屬於android部門 Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; zhangsan.name = @"zhangsan"; zhangsan.height = @(1.90); zhangsan.birthday = [NSDate date]; zhangsan.depart = iosDepart; Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; lisi.name = @"lisi"; lisi.height = @2.0; lisi.birthday = [NSDate date]; lisi.depart = andrDepart; // 直接保存數據庫 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } } #pragma mark 讀取員工 -(IBAction)readEmployee{ // 讀取ios部門的員工 // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置過濾條件 直接使用點語法,注意這裏的depart是關係名 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"); } //NSLog(@"%@",emps); //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 部門 %@",emp.name,emp.depart.name); } }
#pragma mark 分頁查詢 -(void)pageSeacher{ // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 3.設置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 總有共有15數據 // 每次獲取6條數據 // 第一頁 0,6 // 第二頁 6,6 // 第三頁 12,6 3條數據, // 分頁查詢 limit 0,5 // 分頁的起始索引 request.fetchOffset = 12; // 分頁的條數 request.fetchLimit = 6; //依然能夠是獲取6條,但只是獲得3條 NSArray *emps = [_context executeFetchRequest:request error:nil]; //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
#pragma mark 模糊查詢 -(IBAction)readEmployee{ // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 名字以"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.執行請求 NSArray *emps = [_context executeFetchRequest:request error:nil]; //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
有時候咱們須要創建兩個數據庫,但建立2個Data Model文件,採用如下方法,bundles爲nil,會把bundles裏面的全部模型文件的表放在一個數據庫。sql
//NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];數據庫
這個時候咱們須要換另一個方法:fetch
//讀取本地的Data Model文件 NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
注意的是,不一樣的數據庫,要創建不一樣的上下文atom