iOS之CoreData

来源:互联网 发布:蚂蚁讨厌什么味道 知乎 编辑:程序博客网 时间:2024/06/16 19:40

CoreData步骤:
一、创建模型文件(相当于数据库中的表)
二、添加实体(相当于数据库中的某一张表)
a>:实体名字首字母必须大写
b>:属性必须小写
三、创建实体类 coreData会把基本数据类型转换为对象
四、生成上下文,关联模型文件,生成数据库

1.创建新模型文件,CoreData->Data Model
AddEntity->AddAttributes->Relationships(修改O&M)。
再创建文件,CoreData ->NSManagedObject subclass,将Entity添加到其中,自动生成类

这里写图片描述

viewcontroller.m-(void)viewDidload{//上下文初始化self.context = [[NSManagedObjectContext alloc]init];//一个数据持久化助理关联文件self.context.persistentStoreCoordinator = nil;NSManagedObjectModel * model = [[NSManagedObjectModel alloc]initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"Company"withExtension:@"momd"]];//???NSPersistentStoreCoordinator * store =[[NSPersistentStoreCoordinator alloc]initWithManagedObjjectModel:model];//document路径NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];//存放数据的位置NSString * sqlitePath = [docPath stringByAppendingPathComponent:@"Company.sqlite"];NSLog(@"%@",sqlitePath);    //告诉CoreData关联数据库    //1:告诉coreData存数的类型(SQLite)   //2.告诉coreData存放的位置(document)    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];    self.context.persistentStoreCoordinator = store;}在storyBoard中ViewController中添加四个按钮并关联,实现数据库四个基本操作①.创建员工- (IBAction)createEmployee:(id)sender {for(int i = 0; i < 20; i++){Employee * emps = [NSEntityDescription inserNewObjectForEntityForName:@"Employee"inManagedObjectContext:self.context];emps.name = [NSString stringWithFormat:@"BJS1507%d",i];        emps.age = [NSNumber numberWithInt:arc4random()%20 + 40];        emps.height = @188;//字面量。        //通过实体描述来创建模型对象        [self.context save:nil];②.将员工添加到部门中方式一创建员工Employee * emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];    emp.name = @"张三";    emp.age = @13;    emp.height = @177; 创建部门 Department * dep1 = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];    dep1.departmentname = @"Android";    dep1.departmentno = @10001;    [ dep1 addMyemployee:[NSSet setWithObject:emp]];     [self.context save:nil]; 方式二 Department * ios = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];    ios.departmentname = @"ios";    ios.departmentno  = @10000; Employee * emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];    emp1.name = @"张三";    emp1.age = @22;    emp1.mydepartment = ios; [self.context save:nil];

一、通过谓词查找
“= “查询绝对的字段,和名字相等的数据
NSPredicate * predicate = [NSPredicate predicateWithFormat:@”name = %@”,@”BJS150715”];
request.predicate = predicate ;

二、模糊查询
查找包含的某个字段的数据
NSPredicate * predicate = [NSPredicate predicateWithFormat:@”age CONTAINS%@”,@”4”];
request.predicate = predicate;

三、模糊查询“LIKE” * 在字段前面代表查询后边包含该字段的数据
* 在字段后面反之,也可以当包含来使用,例 7
NSPredicate * predicate = [NSPredicate predicateWithFormat:@”age LIKE %@”,@”5*”];
request.predicate = predicate ;

//读取员工- (IBAction)readEmployee:(id)sender {    //请求    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];***降序排列*** NSSortDescriptor * SD = [NSSortDescriptor sortDescriptorWithKey:@"age"ascending:NO];    request.sortDescriptors = @[SD];    //执行查找    NSArray * array =  [self.context executeFetchRequest:request error:nil  ];    for (Employee * emps in array) {        NSLog(@"name = %@ age = %@ height = %@",emps.name,emps.age,emps.height);    } }
//修改员工- (IBAction)updateEmployee:(id)sender {    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name = %@",@"BJS150712"];    request.predicate = predicate   ;    //执行查找请求 返回数组    NSArray * array = [self.context executeFetchRequest:request error:nil];    if (array) {        for (Employee * emps in array) {            emps.name = @"张涛";            emps.age =@30;            emps.height = @178;            [self.context save:nil];            NSLog(@"name =%@ age = %@",emps.name,emps.age);        }    }}//删除员工- (IBAction)deleteEmployee:(id)sender {    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"BJS"];    request.predicate = predicate   ;    NSArray * array = [self.context executeFetchRequest:request error:nil];    if (array) {        for (Employee * emps in array) {            //删除            [self.context deleteObject:emps];            [self.context save:nil];        }    }   }
0 0