CoreData的使用

之前看关于CoreData的使用都w是很早之前的,对于现在有些不太适用,在网上各种查找和总结之后,写了这篇文章,有兴趣的朋友可以看看。

1.创建工程的时候选择CoreData(不建议)

CoreData的使用_第1张图片
CoreData

创建工程的是选择了CoreData,创建完工程之后,系统会自动生成该文件


CoreData的使用_第2张图片

你也可以通过添加文件达到同样的效果


CoreData的使用_第3张图片

选中文件,往里面添加你想要添加的模型,并对属性进行设置
(ps:Entity首字母必须大写,属性类型也需要规范设置)
CoreData的使用_第4张图片

创建实体模型


CoreData的使用_第5张图片

CoreData的使用_第6张图片
每个模型对应四个文件

2.创建你的Manager类-继承自NSObject

.h文件
#import 
#import 

@interface MyCoreManager : NSObject

/**管理对象, 上下文, 持久性存储模型对象*/
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;

/**单例*/
+ (instancetype)shareInstanceWithStoreName:(NSString *)storeName;

/** 查找 数据*/
- (NSMutableArray *)findByModel:(id)model predicateString: (NSString *)predicateString;

/** 插入 数据 */
- (BOOL)insertModel:(id)model;

/** 删除 数据 */
- (BOOL)removeModel:(id)model predicateString: (NSString *)predicateString;

/** 修改 数据 */
- (BOOL)changeModel:(id)model predicateString: (NSString *)predicateString;
@end

.m文件
#import "MyCoreManager.h"
#import 
#import 

#define Class_NAME(CName) NSStringFromClass([CName class])

@interface MyCoreManager ()
/**被管理的数据模型, 数据结构*/
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;

/**连接数据库的*/
@property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;

/**数据库名*/
@property (nonatomic, strong) NSString *storeName;

@end
static MyCoreManager *coreData;

@implementation MyCoreManager

- (NSManagedObjectContext *)managedObjectContext
{
    if (!_managedObjectContext) {
        
        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
        
        if (coordinator) {
            _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
            [_managedObjectContext setPersistentStoreCoordinator:coordinator];
        }
    }
    return _managedObjectContext;
}


//  managedObjectModel 懒加载
- (NSManagedObjectModel *)managedObjectModel
{
    if (!_managedObjectModel) {
        
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:_storeName withExtension:@"momd"];
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }
    return _managedObjectModel;
}


//  persistentStoreCoordinator 懒加载
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (!_persistentStoreCoordinator) {
        
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", _storeName]];
        NSLog(@"---\nstoreURL: %@",storeURL);
        NSError *error = nil;
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
            abort();
        }
    }
    return _persistentStoreCoordinator;
}


// Returns the URL to the application's Documents directory.获取Documents路径
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


#pragma mark - Methods

//  查
- (NSArray *)findByModel:(id)model predicateString: (NSString *)predicateString
{
    NSError *error = nil;
    NSArray *listArray = [_managedObjectContext executeFetchRequest:[self fetchRequest:Class_NAME(model) predicate:predicateString] error:&error];
    
    NSMutableArray *resultArray = [[NSMutableArray alloc] initWithArray:listArray];;
    //
    //    if (listArray.count >= 1)
    //    {
    //
    //        for (NSManagedObject *manager in listArray)
    //        {
    //
    //            for (NSString *propertyName in [self ClassAttributes:model] )
    //            {
    //                [manager setValue:[model valueForKey:propertyName] forKey:propertyName];
    //            }
    //            [resultArray addObject:model];
    //        }
    //    }
    return resultArray;
}


//  插入 数据
- (BOOL)insertModel:(id)model
{
    NSManagedObject *manager = [NSEntityDescription insertNewObjectForEntityForName:Class_NAME(model) inManagedObjectContext:_managedObjectContext];
    
    for (NSString *propertyName in [self ClassAttributes:model]) {
        [manager setValue:[model valueForKey:propertyName] forKey:propertyName];
    }
    
    BOOL result = [self saveContext];
    return result;
    
    
}


//  删除 数据
- (BOOL)removeModel:(id)model predicateString: (NSString *)predicateString
{
    NSError * error = nil;
    NSArray * listArray = [_managedObjectContext executeFetchRequest:[self fetchRequest:Class_NAME(model) predicate:predicateString] error:&error];
    
    if (listArray.count > 0) {
        for (NSManagedObject *manager in listArray) {
            
            [_managedObjectContext deleteObject:manager];
        }
    }
    return [self saveContext];
}


//  改
- (BOOL)changeModel:(id)model predicateString: (NSString *)predicateString
{
    NSError * error = nil;
    NSArray * listArray = [_managedObjectContext 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];
            }
        }
    }
    return [self saveContext];
}


//  读取数据请求 ( 连接 请求 )
- (NSFetchRequest *)fetchRequest:(NSString *)entityName predicate:(NSString *)predicateString
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:_managedObjectContext]];
    
    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 - save
- (BOOL)saveContext
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    if (context) {
        
        NSError *error = nil;
        if ([context hasChanges] && ![context save:&error]) {
            abort();
            return NO;
        }
    }
    return YES;
}

//  单例
+ (instancetype)shareInstanceWithStoreName:(NSString *)storeName
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        coreData = [[self alloc] init];
        coreData.storeName = storeName;
    });
    return coreData;
}


@end

3.调用

1.引入模型文件,和你创建的模型名字相同的那个
2.引入你的管理类

增
    MyCoreManager * coreData = [MyCoreManager shareInstanceWithStoreName:@"MyData"];
    Student * stu = [[Student alloc]initWithEntity:[NSEntityDescription entityForName:@"Student" inManagedObjectContext:coreData.managedObjectContext] insertIntoManagedObjectContext:nil];
    stu.name = @"alex";
    stu.age = @"12";
    [coreData insertModel:stu];
查
    MyCoreManager * coreData = [MyCoreManager shareInstanceWithStoreName:@"MyData"];
    Student * stu = [[Student alloc]initWithEntity:[NSEntityDescription entityForName:@"Student" inManagedObjectContext:coreData.managedObjectContext] insertIntoManagedObjectContext:nil];
    
    NSMutableArray * StuArr = [coreData findByModel:stu predicateString:@"name = 12 AND age = 12"];
    
    for (Student * stuModel in StuArr) {
        MyModel * model = [[MyModel alloc]init];
        model.name = stuModel.name;
        model.age = stuModel.age;
        [_datas addObject: model];
    }

//删
- (BOOL)removeModel:(id)model predicateString: (NSString *)predicateString
//改
- (BOOL)changeModel:(id)model predicateString: (NSString *)predicateString

三点要注意:
(1) shareInstanceWithStoreName:@"MyData"]中的MyData是你所创建的model文件名
(2) 对象初始化不能简单的alloc init ,需要按上面代码的歌声进行初始化,否则调用对象就会导致程序崩溃
(3)谓词(predicateString)的使用,不懂的同学可以戳这里http://www.jianshu.com/p/3da75e023b9c

你可能感兴趣的:(CoreData的使用)