本文仅对CoreData的增、删、该、查操作做简单封装。之所以说是简单封装,是因为本次封装不涉及多线程。
思路:创建一个单例类CoreDataManager--->添加属性:NSManagedObjectModel、NSPersistentStoreCoordinator、
NSManagedObjectContext--->重写该类初始化方法:在方法中初始化NSManagedObjectContext对象--->重写set方法
(NSPersistentStoreCoordinator、NSManagedObjectContext)--->封装增、删、该、查操作。
1.准备工作
.m文件中导入“#import <CoreData/CoreData.h>”并添加属性:
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
2.创建单例类
static CoreDataManager*__manager;
//创建单例类
+(instancetype)shareManager{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
__manager=[[self alloc]init];
});
return __manager;
}
3.重写init方法
/*
*1、初始化方法,初始化 NSManagedObjectContext
*2、NSManagedObjectContext:被管理者对象上下文 相当于一个临时数据库 我们存储或者查询都是通过这个对象来的
*3、NSPersistentStoreCoordinator:文件存储助理,相当于数据库的链接器,它是CoreData的核心 负责链接所有的模块, 包括真实的存储文件;
*/
-(id)init{
if (self=[super init]) {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return self;
}
4.set方法:persistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
//CoreData是建立在SQLite之上的,数据库名称需与.cdatamodel文件同名
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Model.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
// 加载sqlite数据库文件
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
//获取沙盒Documents目录中文件的URL
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
5.set方法:managedObjectModel
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
// xcdataModeld文件编译后为momd文件,从资源文件加载NSManagedObjectModel
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
6.保存文件
//添加、删除操作执行后,需要调用该方法保存文件
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
7.添加数据
//第一种插入操作(根据字典传递数据)
-(BOOL)insertObjectWithEntity:(NSString*)entity parameter:(NSDictionary*)param{
NSManagedObject*object=[NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:_managedObjectContext];
for (NSString*key in param.allKeys) {
[object setValue:param[key] forKey:key];
}
return YES;
}
//第二种插入操作(利用Block)
-(BOOL)insertObjectWithEntity:(NSString*)entity completion:(XHInsertBlock)completionHandle{
NSManagedObject*object=[NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:_managedObjectContext];
completionHandle(object);
if (object) {
return YES;
}else{
return NO;
}
}
举例:
//第一种:
NSDictionary*dic=@{@"name":@"Kevin"};
[_manager insertObjectWithEntity:@"People" parameter:dic];
[_manager saveContext];
//第二种:
[_manager insertObjectWithEntity:@"People" completion:^(NSManagedObject *object) {
[object setValue:@"Tom" forKey:@"name"];
}];
[_manager saveContext];
8.查询数据
-(NSArray*)queryWithEntity:(NSString*)entity predicate:(NSPredicate*)predicate sortKey:(NSString*)key ascending:(BOOL)isAscending{
//创建取回数据请求
NSFetchRequest*request=[[NSFetchRequest alloc]init];
//设置检索的实体描述
NSEntityDescription*entityDes=[NSEntityDescription entityForName:entity inManagedObjectContext:_managedObjectContext];
[request setEntity:entityDes];
//谓词,筛选数据
request.predicate=predicate;
//指定对检索结果的排序方式
if ( key ){
//之所以添加判断,是因为如果key为nil,NSSortDescriptor则无法初始化,程序会奔溃
NSSortDescriptor*sortDestor=[[NSSortDescriptor alloc]initWithKey:key ascending:isAscending];
[request setSortDescriptors:@[sortDestor]];
}
NSError*error=nil;
//执行请求,返回数组
NSArray*fetchedResult=[_managedObjectContext executeFetchRequest:request error:&error];
if (!fetchedResult) {
NSLog(@"error:%@ ,%@",error,[error userInfo]);
}
return fetchedResult;
}
举例:
//查询sex=@"Man"的people对象,按照age的升序排列
NSPredicate*predicate=[NSPredicate predicateWithFormat:@"sex=%@",@"Man"];
dataArray=[_manager queryWithEntity:@"People" predicate:predicate sortKey:@"age" ascending:YES];
9.修改数据
修改数据建立在查询数据的基础上。查询数据的方法返回的是存储数据的内存地址的指针变量。因此,可以通过指针变量对其指向的内存修改数据。
举例:
People*people=(People*)dataArray[0];
people.name=@"Tom";
people.age=18;
10.删除数据
-(BOOL)deleteObject:(NSManagedObject*)object{
if (object && [object isKindOfClass:[NSManagedObject class]]) {
[_managedObjectContext deleteObject:object];
return YES;
}
return NO;
}
举例:
People*people=(People*)dataArray[0];
[_manager deleteObject:people];
[_manager saveContext];