iOS CoreData 使用

CoreData是iOS5之后才出现的一个框架,提供了直接使用SQLite数据库的大部分灵活性,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象,通过CoreData管理应用程序的数据模型,可以极大程度减少需要编写的代码数量!

CoreData的简单封装(增、删、改、查)


获取上下文

#pragma mark - Getter
- (NSManagedObjectContext *)context{
    if (!_context){
        AppDelegate *delegate = (AppDelegate *)UIApplication.sharedApplication.delegate;
        _context = delegate.persistentContainer.viewContext;
    }
    return _context;
}

1.添加数据

pragma mark - 添加数据
- (BOOL)insertWithTableName:(NSString *)tableName propertits:(NSDictionary *)propertits{
    NSManagedObject *entity = [NSEntityDescription insertNewObjectForEntityForName:tableName inManagedObjectContext:self.context];
    for (NSString *key in propertits.allKeys) {
        id value = [propertits objectForKey:key];
        [entity setValue: value forKey:key];
    }
    NSError *error = nil;
    if (![self.context save:&error]){
        NSLog(@"%@",error);
        return false;
    }else{
        return true;
    }
}


2.删除数据

#pragma mark - 删除数据
- (BOOL)deleteWithTableName:(NSString *)tableName predicate:(NSPredicate *)predicate{
    NSError *error = nil;
    NSFetchRequest *fetchRequst = [NSFetchRequest fetchRequestWithEntityName:tableName];
    fetchRequst.predicate = predicate;

    NSMutableArray *result = [[self.context executeFetchRequest:fetchRequst error:&error] mutableCopy];
    for (id obj in result) {
        [self.context deleteObject:obj];
    }
    if (![self.context save:&error]){
        NSLog(@"%@",error);
        return false;
    }else{
        return true;
    }
}
- (BOOL)deleteWithTableName:(NSString *)tableName{
    return [self deleteWithTableName:tableName predicate:nil];
}


3.修改数据


#pragma mark - 修改数据
- (BOOL)modifyWithTableName:(NSString *)tableName predicate:(NSPredicate *)predicate properties:(NSDictionary *)propertites{
    NSError *error = nil;
    NSFetchRequest *fetchRequst = [NSFetchRequest fetchRequestWithEntityName:tableName];
    fetchRequst.predicate = predicate;
    NSMutableArray *result = [[self.context executeFetchRequest:fetchRequst error:&error] mutableCopy];
    for (id obj in result) {
        for (NSString *key in propertites.allKeys) {
            id value = [propertites objectForKey:key];
            [obj setValue:value forKey:key];
        }
    }
    if (![self.context save:&error]){
        NSLog(@"%@",error);
        return false;
    }else{
        return true;
    }
}


4.查询数据 <异步和同步查询>

#pragma mark - 查询数据
- (void)queryAsyncWithTableName:(NSString *)tableName predicate:(NSPredicate *)predicate sort:(NSSortDescriptor *)sort fetchResultHandler:(FetchResultHandlder)handler{
    
    NSFetchRequest *fetchRequst = [NSFetchRequest fetchRequestWithEntityName:tableName];
    
    if (sort.key != nil){
        fetchRequst.sortDescriptors = @[sort];
    }
    NSAsynchronousFetchRequest *asyncFetchRequst = [[NSAsynchronousFetchRequest alloc]initWithFetchRequest:fetchRequst completionBlock:^(NSAsynchronousFetchResult * result) {
        NSArray *rst = result.finalResult;
        handler(rst);
    }];
    
    NSError *error = nil;
    if (![self.context executeRequest:asyncFetchRequst error:&error]){
        NSLog(@"%@",error);
    }
}
- (void)queryAsyncWithTableName:(NSString *)tableName fetchResultHandler:(FetchResultHandlder)handler{
    [self queryAsyncWithTableName:tableName predicate:nil sort:[[NSSortDescriptor alloc]init] fetchResultHandler:handler];
}

- (void)querySyncWithTableName:(NSString *)tableName predicate:(NSPredicate *)predicate sort:(NSSortDescriptor *)sort fetchResultHandler:(FetchResultHandlder)handler{
    
    NSFetchRequest *fetchRequst = [NSFetchRequest fetchRequestWithEntityName:tableName];
    
    fetchRequst.predicate = predicate;
    
    if (sort.key != nil){
        fetchRequst.sortDescriptors = @[sort];
    }
    
    NSError *error = nil;
    NSArray * result = [self.context executeFetchRequest:fetchRequst error:&error];
    if (![self.context save:&error]){
        NSLog(@"%@",error);
    }
    handler(result);
}

- (void)querySyncWithTableName:(NSString *)tableName fetchResultHandler:(FetchResultHandlder)handler{
    [self querySyncWithTableName:tableName predicate:nil sort:[[NSSortDescriptor alloc]init] fetchResultHandler:handler];
}

参考:
https://www.jianshu.com/p/332cba029b95

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