首页 > 代码库 > CoreData

CoreData

封装CoreManager类

@implementation CoreDataManager

{

    //上下文

    NSManagedObjectContext *_ctx;

}

 //单例

+(instancetype)sharedManager

{

    

    static CoreDataManager *manager = nil;

    

    static dispatch_once_t onceToken;

    

    dispatch_once(&onceToken, ^{

        manager = [[CoreDataManager alloc] init];

    });

    return manager;

    

}

 //初始化时,同事初始化相关的

-(instancetype)init

{

    self = [super init];

    if (self) {

        //初始化上下文对象

        //1.关联实体描述文件(User.xcdatamodeld)

        //扩展名写@“momd”

        NSString *path = [[NSBundle mainBundle] pathForResource:@"GuoFuBao" ofType:@"momd"];

        NSURL *url = [NSURL fileURLWithPath:path];

        

        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];       

        //2.关联数据库文件

        NSPersistentStoreCoordinator *coor = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

        

        //数据库文件的路径

        NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/gfb.sqlite"];

        NSLog(@"path=%@",dataPath);

        

        NSURL *dataUrl = [NSURL fileURLWithPath:dataPath];

               //CoreData管理的数据库文件升级时传参

        NSDictionary *optionDict = @{NSMigratePersistentStoresAutomaticallyOption:[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption:[NSNumber numberWithBool:YES]};

        

        [coor addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dataUrl options:optionDict error:nil];

        

        //3.上下文对象

        _ctx = [[NSManagedObjectContext alloc] init];

        _ctx.persistentStoreCoordinator = coor;

        

    }

    return self;

}

 

增(插入)

//插入数据- (IBAction)insertData{    NSLog(@"插入数据");    //创建模型数据模型    Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedContext];    student.name = @"张三2";    student.id = @(11);    Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:self.managedContext];    book.bookID = @(121);    book.bookName = @"<老人与海2>";    student.book = book;    Student *student2 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedContext];    student2.name = @"李四2";    student2.id = @(23);    Book *book2 = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:self.managedContext];    book2.bookID = @(242);    book2.bookName = @"<飞鸟集2>";    student2.book = book2;    //保存,用 save 方法    NSError *error = nil;    BOOL success = [self.managedContext save:&error];    if (!success) {        [NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];    }}

删(删除)

//删除- (IBAction)removeData:(id)sender{    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];    //查到到你要删除的数据库中的对象    NSPredicate *predic = [NSPredicate predicateWithFormat:@"name = %@",@"张三2"];    request.predicate = predic;    //请求数据    NSArray *objs = [self.managedContext executeFetchRequest:request error:nil];    for (Student *stu in objs) {        [self.managedContext deleteObject:stu];    }    [self.managedContext save:nil];}

/读取数据库文件- (IBAction)readData{    NSLog(@"读取数据");    dispatch_async(dispatch_get_main_queue(), ^{        // 初始化一个查询请求        //  NSFetchRequest *request = [[NSFetchRequest alloc] init];        // 设置要查询的实体        // request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedContext];        //以上代码简写成下边        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];        // 设置排序(按照age降序)        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:NO];        request.sortDescriptors = [NSArray arrayWithObject:sort];        // 设置条件过滤(搜索name中包含字符串"zhang"的记录,注意:设置条件过滤时,数据库SQL语句中的%要用*来代替,所以%Itcast-1%应该写成*zhang*)        // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];        // request.predicate = predicate;        // 执行请求        NSError *error = nil;        NSArray *objs = [self.managedContext executeFetchRequest:request error:&error];        if (error) {            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];        }        NSLog(@"-----------------------------------");        // 遍历数据        int index = 0;        for (NSManagedObject *obj in objs) {            NSLog(@"%d---name=%@", index++,[obj valueForKey:@"name"]);        }        for (Student *stu in objs) {            Book *book = stu.book;            NSLog(@"%@---name=%@", stu.name,book.bookName);        }    });}

改(更新)

//更新数据- (IBAction)modifyData{    // 如果是想做更新操作:只要在更改了实体对象的属性后调用[context save:&error],就能将更改的数据同步到数据库    //先从数据库中取出所有的数据,然后从其中选出要修改的那个,进行修改,然后保存    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];    //设置过滤条件    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"李四2"];    request.predicate = pre;    NSError *error = nil;    NSArray *objs = [self.managedContext executeFetchRequest:request error:&error];    if (error) {         [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];    }    // 2.更新身高    for (Student *stu in objs) {        stu.name = @"被修改的新名字";    }   //保存,用 save 方法   BOOL success = [self.managedContext save:&error];   if (!success) {       [NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];   }}

 

 

 

 

 

 

 

 

CoreData