CoreData的简单使用

2016-11-22  本文已影响43人  天外丶飞仙

CoreData入门

CoreData简介

CoreData涉及到的类简单介绍

Coredata使用前的准备工作

   //获取momd文件的路径
    NSString * path = [[NSBundle mainBundle] pathForResource:@"AnimalModel" ofType:@"momd"];
    //把路径转换为url
    NSURL * url = [[NSURL alloc] initFileURLWithPath:path];
    //获取被管理对象的模型
    NSManagedObjectModel * model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
    //创建一个持久化得存储协调器将数据库模型关联起来
    NSPersistentStoreCoordinator * coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    //设置需要关联的路径
    NSString * str = NSHomeDirectory();
    NSLog(@"%@", str);
    NSString * dbPath = [str stringByAppendingString:@"/Documents/coreData.sqlite"];
    NSURL * url2 = [[NSURL alloc] initFileURLWithPath:dbPath];
    //关联数据库路径
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url2 options:nil error:nil];
    //创建上下文
    _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    //将数据协调器设置给上下文
    _context.persistentStoreCoordinator = coordinator;

//根据上下文拿到数据模型
    Dog * model = [NSEntityDescription                  insertNewObjectForEntityForName:@"Dog" inManagedObjectContext: _context];
    model.age = [[NSNumber alloc] initWithInt:18];
    model.name = @"张全蛋";


//创建请求对象
NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName:@"Dog"];
//这里可以使用谓词设置查询条件
//拿到查询到的数组
    NSArray * array = [_context executeFetchRequest:request error:nil];

MagiclRecord

MagicalRecord 致力于更快捷和容易的使用CoreData。MagicalRecord 致力于使CoreData的代码更简洁,更简单的获取数据,并且使用最优化的操作,它提供了方便的方法,包含了CoreData使用的查询更新等的公用模板,降低了CoreData的使用门槛

上一篇下一篇

猜你喜欢

热点阅读