美文网首页
CoreData 异步存储和获取数据

CoreData 异步存储和获取数据

作者: fordG | 来源:发表于2018-09-17 16:24 被阅读0次

    CoreData 异步存储和获取数据

    关键字:parentContext  NSAsynchronousFetchRequest
    

    .xcdatamodeld文件创建(自己手动创建)

    创建数据库.png 实体加入注意右边事项.png 创建NSManagedObject.png

    异步存储数据

    CoreDataManager 单例模式

    //mainContext主线程, backgroundContext private线程
    @property (nonatomic, strong) NSManagedObjectContext *mainContext;
    @property (nonatomic, strong) NSManagedObjectContext *backgroundContext;
    
    
    /**
     创建上下文对象
     */
    - (NSManagedObjectContext *)contextWithModelName:(NSString *)modelName {
        // 创建上下文对象,并发队列设置为主队列
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        
        // 创建托管对象模型,并使用Company.momd路径当做初始化参数
        NSURL *modelPath = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
        
        // 创建持久化存储调度器
        NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 创建并关联SQLite数据库文件,如果已经存在则不会重复创建
        NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        dataPath = [dataPath stringByAppendingFormat:@"/%@.sqlite", modelName];
        [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:nil];
        
        // 上下文对象设置属性为持久化存储器
        context.persistentStoreCoordinator = coordinator;
        
        return context;
    }
    
    //懒加载
    - (NSManagedObjectContext *)mainContext{
        if (!_mainContext) {
            _mainContext = [self contextWithModelName: @"Mine"];
        }
        return _mainContext;
    }
    
    - (NSManagedObjectContext *)backgroundContext{
        if (!_backgroundContext) {
            _backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
            _backgroundContext.parentContext = _mainContext;
        }
        return _backgroundContext;
    }
    
    /**
     *   将实体类和模型文件建立联系
     *
     *   @param class 传入一个你要操作的实体类的类名
     *
     *   @return 返回一 NSManagedObject的对象
     */
    + (id)insertNewObjectForEntityForName:(Class)modelClass
    {
        CoreDataManager *manager = [CoreDataManager manager];
        NSManagedObject  *mgrObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass(modelClass) inManagedObjectContext: manager.backgroundContext];
        return mgrObject;
    }
    
    /**
     *   保存数据
     *
     *   @param error  error 传& error
     *
     *   @complete  返回是否成功
     */
    + (void)save:(NSError * __autoreleasing *)error complete: (void(^)(BOOL))complete
    {
        CoreDataManager *manager = [CoreDataManager manager];
        [manager.backgroundContext performBlock:^{
            NSLog(@"currentThread: %@", [NSThread currentThread]);
            [manager.backgroundContext save: error];
            [manager.mainContext performBlock:^{
                NSLog(@"currentThread: %@", [NSThread currentThread]);
                complete([manager.mainContext save: error]);
            }];
        }];
    }
    

    数据的异步加入

    + (void)addImageModelWithData: (NSData *)data complete:(void (^)(BOOL, ImageModel *))complete{
        
        ImageModel *model = [CoreDataManager insertNewObjectForEntityForName: [ImageModel class]];
        model.content = data;
        //保存
        [CoreDataManager save:nil complete:^(BOOL result) {
            if (result) {
                complete(result, model);
            }
        }];
    }
    

    异步获取数据

    + (void)executeFetchRequest:(Class)entityClass predicate:(NSPredicate *)predicate complete:(complete)complete
    {
        CoreDataManager *manager = [CoreDataManager manager];
        //创建一个请求对象 (填入要查询的表名-实体类)
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass(entityClass)];
        request.predicate = predicate;
        NSError *error = nil;
        NSAsynchronousFetchRequest *asyRequest = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:request completionBlock:^(NSAsynchronousFetchResult * _Nonnull result) {
            if (complete) {
    //            NSLog(@"currentThread: %@", [NSThread currentThread]);
                complete(result.finalResult, error);
            }
        }];
        
        [manager.mainContext executeRequest: asyRequest error: &error];
    }
    

    DEMO地址

    相关文章

      网友评论

          本文标题:CoreData 异步存储和获取数据

          本文链接:https://www.haomeiwen.com/subject/itqrnftx.html