CoreData的使用

这边我将如何使用CoreData的示例代码记录下来,不再截图说明如何创建model模型了,截图上传麻烦(公司网限速)

#import 
#import 
#import "Student+CoreDataClass.h"


@interface CQ_CoreDataSource : NSObject

- (BOOL)insertDataWithModel:(Student *)model;

- (BOOL)delegateWithKey:(NSString *)key predicate:(id)pre;


- (BOOL)updateWithKey:(NSString *)key predicate:(NSString *)pre NewValue:(NSString *)NewValue;

- (NSArray *)readDatWithKey:(NSString *)Key predicate:(NSString *)pre;

-(NSArray *)sortData;
@end

下面是.m中的实现代码

#import "CQ_CoreDataSource.h"

@interface CQ_CoreDataSource ()
{
    NSManagedObjectContext * _context;
    NSMutableArray * _dataSource;
}
@end

@implementation CQ_CoreDataSource
- (instancetype)init
{
    if (self = [super init]) {
        [self creatSqlite];
    }
    return self;
}

- (void)creatSqlite{
    //创建模型对象
    //获取模型路径
    NSURL *modelUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];

    //根据模型文件创建模型对象
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];
    //创建持久化存储助理:数据库
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];

    //数据库的名称和路径
    NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *sqlitePath = [docStr stringByAppendingPathComponent:@"coreData.sqlite"];
    NSLog(@"数据库 path = %@", sqlitePath);
    NSURL *sqlUrl = [NSURL fileURLWithPath:sqlitePath];
    NSError *error = nil;
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:&error];
    if (error) {
        NSLog(@"添加数据库失败:%@",error);
    }else
    {
         NSLog(@"添加数据库成功");
    }

    //创建上下文 保存信息,操作数据库
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    //关联持久化助理
    context.persistentStoreCoordinator = store;

    _context = context;


}


- (BOOL)insertDataWithModel:(Student *)model
{
    Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];

    student.age = 10;
    student.name = @"陈强";
    student.sex = @"M";
    student.height = 179;
    student.number = 90;

    NSError *error = nil;
    if ([_context save:&error]) {
        NSLog(@"插入数据库成功");
        return YES;
    }else{
        NSLog(@"插入数据库失败");
        return NO;
    }
}


- (BOOL)delegateWithKey:(NSString *)key predicate:(id)pre{

    //创建删除请求
    NSFetchRequest *deleRequest = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    //删除条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < %d",11];
    deleRequest.predicate = predicate;

    //返回需要删除的对象数组
    NSArray *deleArray = [_context executeFetchRequest:deleRequest error:nil];

    //从数据库中删除
    for (Student *stu in deleArray) {
        [_context deleteObject:stu];
    }

    NSError *error = nil;
    //保存--记住保存
    if ([_context save:&error]) {
       NSLog(@"删除 age < 10 的数据");
        return YES;
    }else{
        NSLog(@"删除数据失败, %@", error);
        return NO;
    }
}


- (BOOL)updateWithKey:(NSString *)key predicate:(NSString *)pre NewValue:(NSString *)NewValue
{
    NSString *str = [NSString stringWithFormat:@"%@ == '%@'",key,pre];

    //创建查询请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
    request.predicate = predicate;
    //发送请求
    NSArray *resArray = [_context executeFetchRequest:request error:nil];

    //修改
    for (Student *stu in resArray) {
        stu.name = NewValue;
    }

    //保存
    NSError *error = nil;
    if ([_context save:&error]) {
        NSLog(@"保存成功");
        return YES;
    }else{
        NSLog(@"保存失败");
        return NO;
    }

}


- (NSArray *)readDatWithKey:(NSString *)Key predicate:(NSString *)pre
{
    //创建查询请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    //查询条件
    NSString *str = [NSString stringWithFormat:@"%@ == '%@'",Key,pre];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
    request.predicate = predicate;

//    //从第几页开始查询
//    request.fetchOffset = 0;
//    
//    //每页显示多少条数据
//    request.fetchLimit = 6;
//    
    NSArray *array = [_context executeFetchRequest:request error:nil];

    return array;
}


-(NSArray *)sortData{
    //创建排序请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];

    //实例化排序对象
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    NSSortDescriptor *number = [NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES];
    request.sortDescriptors = @[sort,number];

    //发送请求
    NSError *error = nil;
    NSArray *resArray = [_context executeFetchRequest:request error:&error];


    if (error == nil) {
        NSLog(@"排序成功");
    }else
    {
        NSLog(@"排序失败");
    }
    return resArray;

}

上面的搜索过滤条件是我自己随意写的,自己根据项目需要修改,等周末无事时,我在讲完整的如何创建model模型的图文补上,结合起来在看会比较轻松点,

你可能感兴趣的:(CoreData)