CoreData 的简要利用__ 01

注:使用coreData 记得导入 #import <CoreData/CoreData.h>

1.创制模型文件Company.xcdatamodeld

2.添加实体(表)Employee

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

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”;

emp.height=@1.81;

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) {

emp.height=@2.0;

}

//保存

[_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];

}

网站地图xml地图