CoreData 的简单使用__ 01

注:使用coreData 记得导入 #import


1.创建模型文件Company.xcdatamodeld


CoreData 的简单使用__ 01_第1张图片

2.添加实体(表)Employee


CoreData 的简单使用__ 01_第2张图片

3.创建实体类(相当于模型)Employee.h/.m文件


CoreData 的简单使用__ 01_第3张图片

4.生成上下文 (这里我为了方便定义一个全局的上下文)

NSManagedObjectContext*context = [[NSManagedObjectContextalloc]init];

//5.上下文关联数据库

NSManagedObjectModel*model = [NSManagedObjectModel mergedModelFromBundles:nil];//就是1(模型文件)

NSPersistentStoreCoordinator*store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];//持久化存储调度器

//告诉coreData数据库的名字和路径

NSString*doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];

NSString*sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];

[store addPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nil URL:[NSURLfileURLWithPath:sqlitePath]options:nilerror:nil];

context.persistentStoreCoordinator= store;

_context= context; //把全局的赋值下

上下文有了之后就可以进行增删改查操作了。


5.添加

- (void)addEmployee {

//1.创建员工对象

Employee*emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"inManagedObjectContext:_context];

emp.name=@"JasoneIo";

[email protected];

emp.birthday= [NSDate date];

NSError*error =nil;

[_contextsave:&error];

if(error) {

NSLog(@"%@",error);

}

}

6.读取

- (void)readEmployee {

// 1.抓取请求对象

NSFetchRequest*request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];

//2.设置过滤条件

//NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"JasoneIo2"];

//request.predicate = pre;

//3.设置排序

//按照身高来排序(升序排序)

NSSortDescriptor*heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];

request.sortDescriptors=@[heightSort];

//4.执行请求

NSArray*arr = [_context executeFetchRequest:requesterror:nil]; //这个语句返回的是一个数组,数组里面包含的类型就是 模型

for (Employee*emp in arr) {

NSLog(@"%@_%@_%@",emp.name,emp.height,emp.birthday);

}

}

7.更新

- (void)updateEmployee {

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];

//2.设置过滤条件

NSPredicate*pre = [NSPredicate predicateWithFormat:@"name = %@",@"JasoneIo2"];

request.predicate= pre;

//4.执行请求

NSArray*arr = [_context executeFetchRequest:requesterror:nil];

for (Employee*emp in arr) {

[email protected];

}

//保存

[_context save:nil];

}

8.删除

- (void)deleteEmployee {

NSFetchRequest*request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];

//2.设置过滤条件

NSPredicate*pre = [NSPredicate predicateWithFormat:@"name = %@",@"JasoneIo"];

request.predicate= pre;

//4.执行请求

NSArray *arr = [_context executeFetchRequest:request error:nil];

for (Employee*emp in arr) {

[_context deleteObject:emp];//删除

}

//保存

[_context save:nil];

}

你可能感兴趣的:(CoreData 的简单使用__ 01)