美文网首页
iOS Coredata的抽象管理类

iOS Coredata的抽象管理类

作者: KimmyKing | 来源:发表于2017-12-06 16:36 被阅读0次

    如何来设计这个抽象类,我们可以根据oo(面向对象)的思想先来分析一下有哪些对象,这有对象又有哪些行为.

    对象:    

    ①管理者,manager类,为了线程安全,这个变量应该是全局的.

    ②表,Entity对象

    行为:

    ①创建数据库,不需暴露,创建一次就可以

    ②增加数据,需暴露的接口

    ③删除数据,需暴露的接口

    ④修改数据,需暴露的接口

    ⑤查询数据,需暴露的接口



    一    实例化manager类:

    static CoreDataManager *_manager;

    + (instancetype)shareManager

    {

    return [[self alloc] init];

    }

    + (instancetype)allocWithZone:(struct _NSZone *)zone

    {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

    _manager = [super allocWithZone:zone];

    });

    return _manager;


    NSManagedObjectContext:An object representing a single object space or scratch pad that you use to fetch, create, and save managed objects.

    官方文档的意思是需要通过这个上下文对象来进行对coredata的增删改查操作.

    所以manger就需要拥有Context这个属性

    @interface CoreDataManager()

    @property (nonatomic , strong)NSManagedObjectContext *context;

    @end

    通过懒加载的方式来实例化content,并创建数据库

    - (NSManagedObjectContext *)context

    {

    if (!_context) {

    //1.经过编译后数据模型文件的扩展名由xcdatamodeld变成了momd

    NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];

    //2.构建CoreData的模型文件

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

    //3.通过模型文件创建PersistentStoreCoordinator对象

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

    //4.数据库存储路径URL

    NSURL *dbUrl = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"test.sqlite"]];

    //5.设置persistStore的持久化存储方式为SQLiteStoreType,代表persistStore会自动生成一个SQLite数据库文件来实现持久化存储,并会自动生成SQL语句来做CRUD(增删改查)

    /***************************************************数据库升级*****************************************************************************/

    NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],

    NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption, nil];

    if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbUrl options:optionsDictionary error:nil]) {

    NSLog(@"failed to add persistent store with type to persistent store coordinator");

    }

    /****************************************************************************************************************************************/

    //6.NSManagedObjectContext:所有的ManagedObject的增删改查都是在context上进行的。

    //NSMainQueueConcurrencyType:这个context所关联的控制器和UI控件只能在主线程中使用

    _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    _context.persistentStoreCoordinator = coordinator;

    return _context;

    }



    二    提供增删改查的接口的内部实现

    //MARK: -

    //MARK: --插入数据

    - (void)insertParameter:(NSDictionary *)parameter tableName:(NSString *)tableName

    {

    NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:tableName inManagedObjectContext:self.context];

    for (NSString *key in parameter.allKeys) {

    [obj setValue:parameter[key] forKey:key];

    }

    if ([self.context save:nil]) {

    NSLog(@"save success");

    }else{

    NSLog(@"save failure");

    }

    }

    //MARK: -

    //MARK: --删除

    - (void)deleteDataWithTableName:(NSString *)tableName predicate:(NSPredicate *)predicate

    {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:tableName];

    request.predicate = predicate;

    NSArray *results = [self.context executeFetchRequest:request error:nil];

    for (NSManagedObject *obj in results) {

    [self.context deleteObject:obj];

    }

    if ([self.context save:nil]) {

    NSLog(@"save success");

    }else{

    NSLog(@"save failure");

    }

    }

    //MARK: -

    //MARK: -- 更新数据

    - (void)updateWithAttribute:(id)attribute key:(NSString *)key tableName:(NSString *)tableName predicate:(NSString *)predicateString

    {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:tableName];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

    request.predicate = predicate;

    NSArray *results = [self.context executeFetchRequest:request error:nil];

    for (NSManagedObject *obj in results) {

    [obj setValue:attribute forKey:key];

    }

    //保存

    if ([self.context save:nil]) {

    NSLog(@"operate success");

    }else{

    NSLog(@"operate failed");

    }

    }

    //MARK: -

    //MARK: --查询数据

    - (NSArray *)selectWithTableName:(NSString *)tableName predicate:(NSString *)predicateString

    {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:tableName];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

    request.predicate = predicate;

    NSArray *results = [self.context executeFetchRequest:request error:nil];

    return results;

    }


    三    导入coredata文件并进行设置



    四    增删改查

    //MARK: -

    //MARK: --增

    - (IBAction)add:(id)sender {

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:1],

    @"name" : @"AAA",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:2],

    @"name" : @"BBB",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:3],

    @"name" : @"CCC",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:4],

    @"name" : @"DDD",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:5],

    @"name" : @"EEE",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:6],

    @"name" : @"FFF",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:7],

    @"name" : @"GGG",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:8],

    @"name" : @"HHH",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:9],

    @"name" : @"III",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:10],

    @"name" : @"JJJ",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:11],

    @"name" : @"KKK",

    } tableName:Table_People];

    [Manager insertParameter:@{

    @"age" : [NSNumber numberWithInt:12],

    @"name" : @"LLL",

    } tableName:Table_People];

    }

    //MARK: -

    //MARK: --删

    - (IBAction)delete:(id)sender {

    [Manager deleteDataWithTableName:Table_People predicate:@"age=1"];

    }

    //MARK: -

    //MARK: --改

    - (IBAction)update:(id)sender {

    [Manager updateWithAttribute:@"KimmyKing" key:@"name" tableName:Table_People predicate:@"name='BBB'"];

    }

    //MARK: -

    //MARK: --查

    - (IBAction)select:(id)sender {

    NSArray *arr = [Manager selectWithTableName:Table_People predicate:@"age>10"];

    for (People *p in arr) {

    NSLog(@"%@今年%@岁了",p.name,p.age);

    }

    }

    五    数据库升级

    当数据库需要增加或修改字段时,原有的数据库就不能使用了,需要使用新的数据库

    最后附上demo链接:戳我

    喜欢点赞哦~

    相关文章

      网友评论

          本文标题:iOS Coredata的抽象管理类

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