上篇文章我们已经把core Data的创建方式以及过程介绍完了,这篇文章主要内容是介绍一个core Data的管理类, 我们对其进行封装, 用的时候直接可以对数据进行增删改查的操作, 用起来十分方便.
core Data主要的几个类:
管理对象模型, 一个模型关联着一个模型文件(. xcdatamodeld),储存着数据库的数据结构
NSManagedObjectModel
持久化存储调度器, 负责协调存储区和上下文之间的关系
NSPersistentStoreCoordinator
管理对象上下文
NSManagedObjectContext
首先要把这几个对象初始化, 这里我们用懒加载的方式:
管理对象模型
- (NSManagedObjectModel *)managedObjectModel{
if (!_managedObjectModel) {
//URL为coreDataTest.xcdatamodeld(你本地的xcdatamodeld名)的
//注意:拓展名应该是momd,而不是xcdatamodeld
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coreDataTest" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return _managedObjectModel;
}
持久化存储调度器
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (!_persistentStoreCoordinator) {
//创建coodinator需要传入的managedObjectModel
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
//指定本地的SQLite数据库文件
NSURL *sqliteURL = [[self documentDirectoryURL] URLByAppendingPathComponent:@"coreDataTest.sqlite"];
NSLog(@"本地SQLite数据库文件路径=%@", sqliteURL);
NSError *error;
//为 persistentStoreCoordinator 制定本地存储的类型, 这里制定的是SQLite
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqliteURL options:nil error:&error];
if (error) {
NSLog(@"failed to create persistentStoreCoordinator__%@", error.localizedDescription);
}
}
return _persistentStoreCoordinator;
}
管理对象上下文
- (NSManagedObjectContext *)context{
if (!_context) {
// 指定context的并发类型:NSMainQueueConcurrencyType 或 NSPrivateQueueConcurrencyType
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_context.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _context;
}
下面这几个是我们初始化以上几个对象时用的几个方法:
#pragma mark --创建document目录
- (nullable NSURL *)documentDirectoryURL
{
return [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
}
#pragma mark --读取数据请求
- (NSFetchRequest *)fetchRequest:(NSString *)entityName predicate:(NSString *)predicateString
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:_context]];
if (predicateString != nil) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
[request setPredicate:predicate];
}
return request;
}
#pragma mark --allAttributes
- (NSMutableArray *)ClassAttributes:(id)classModel
{
NSMutableArray *array = [NSMutableArray array];
NSString *className = Class_Name(classModel);
const char *cClassName = [className UTF8String];
id classM = objc_getClass(cClassName);
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(classM, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
NSString *attributeName = [NSString stringWithUTF8String:property_getName(property)];
[array addObject:attributeName];
}
return array;
}
#pragma mark --保存数据到持久层
- (BOOL)saveContext
{
NSManagedObjectContext *context = [self context];
if (context) {
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
abort();
return NO;
}
}
return YES;
}
这些做完了我们就可以对数据进行增删改查的操作了, 具体的实现如下:
#pragma mark --数据的增删改查
/**
插入数据
*/
- (BOOL)insertModel:(id)model
{
NSManagedObject *manager = [NSEntityDescription insertNewObjectForEntityForName:Class_Name(model) inManagedObjectContext:_context];
for (NSString *propertyName in [self ClassAttributes:model]) {
[manager setValue:[model valueForKey:propertyName] forKey:propertyName];
}
BOOL result = [self saveContext];
if (result) {
NSLog(@"插入数据成功__%@", model);
}else{
NSLog(@"插入数据失败");
}
return result;
}
/**
删除数据
*/
- (BOOL)removeModel:(id)model predicateString:(NSString *)predicateString
{
NSError *error = nil;
NSArray *listArray = [_context executeFetchRequest:[self fetchRequest:Class_Name(model) predicate:predicateString] error:&error];
if (listArray.count > 0) {
for (NSManagedObject *manager in listArray) {
[_context deleteObject:manager];
}
NSLog(@"删除成功");
}else{
NSLog(@"数据为空,无法继续删除");
}
return [self saveContext];
}
/**
修改数据
*/
- (BOOL)changeModel:(id)model predicateString:(NSString *)predicateString
{
NSError *error = nil;
NSArray *listArray = [_context executeFetchRequest:[self fetchRequest:Class_Name(model) predicate:predicateString] error:&error];
if (listArray.count > 0) {
for (NSManagedObject *manager in listArray) {
for (NSString *propertyName in [self ClassAttributes:model]) {
[manager setValue:[model valueForKey:propertyName] forKey:propertyName];
}
NSLog(@"修改成功__%@", manager);
}
}
return [self saveContext];
}
/**
查询数据
*/
- (NSMutableArray *)findByModel:(id)model predicateString:(NSString *)predicateString
{
NSError *error = nil;
NSArray *listArray = [_context executeFetchRequest:[self fetchRequest:Class_Name(model) predicate:predicateString] error:&error];
NSMutableArray *resultArray = [[NSMutableArray alloc] initWithArray:listArray];
return resultArray;
}
这样我们对Core Data的封装就完成了,具体的使用方法如下:
我们要在自己的控制器里面调用上述的几个接口, 对数据进行增删改查,
首先要引入模型类和管理类
#import "Person+CoreDataClass.h"
#import "LCCoreDataManager.h"
然后把我们刚才写好的管理类以及模型文件进行初始化
LCCoreDataManager *coreDataManager = [LCCoreDataManager shareInstanceWithStoreName:@"Person"];
Person *personModel = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:coreDataManager.context] insertIntoManagedObjectContext:nil];
接下来就可以进行相应的增删改查操作了, 这些方法需要放在对应的调用方法里面:
/**
插入数据
*/
- (void)clickInsertBtn
{
LCCoreDataManager *coreDataManager = [LCCoreDataManager shareInstanceWithStoreName:@"Person"];
Person *personModel = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:coreDataManager.context] insertIntoManagedObjectContext:nil];
personModel.name = @"kobe";
personModel.age = 37;
personModel.height = 198;
[coreDataManager insertModel:personModel];
}
/**
删除数据
*/
- (void)clickDeleteBtn
{
LCCoreDataManager *coreDataManager = [LCCoreDataManager shareInstanceWithStoreName:@"Person"];
Person *personModel = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:coreDataManager.context] insertIntoManagedObjectContext:nil];
//predicateString--需要删除的数据的条件
[coreDataManager removeModel:personModel predicateString:@"age = 40"];
}
/**
修改数据
*/
- (void)clickChangeBtn
{
LCCoreDataManager *coreDataManager = [LCCoreDataManager shareInstanceWithStoreName:@"Person"];
Person *personModel = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:coreDataManager.context] insertIntoManagedObjectContext:nil];
//要修改的数据
personModel.name = @"jordon";
personModel.height = 199;
personModel.age = 40;
//需要被修改的数据 (所有age = 37的进行修改)
[coreDataManager changeModel:personModel predicateString:@"age = 37"];
}
/**
查询数据
*/
- (void)clickSearchBtn
{
LCCoreDataManager *coreDataManager = [LCCoreDataManager shareInstanceWithStoreName:@"Person"];
Person *personModel = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:coreDataManager.context] insertIntoManagedObjectContext:nil];
//要查询数据的条件
NSMutableArray *PersonArr = [coreDataManager findByModel:personModel predicateString:@"age = 37"];
NSLog(@"%ld", PersonArr.count);
for (Person *personM in PersonArr) {
NSLog(@"%@=%d=%d", personM.name,personM.age, personM.height);
}
}
以上就是所有的关于Core Data的封装以及具体调用的介绍了,这里只是针对简单的增删改查进行操作, 如需其他需求, 需要根据自己的需要自行进行修改. 下面附上demo的地址, 如还有不懂的地方, 可以看demo上的内容.
https://github.com/LeoTnT/CoreDataDemo