CoreData封装

 Core Data数据持久化是对SQLite的一个升级,它是ios集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类。


   1NSManagedObjectModel(被管理的对象模型)


           相当于实体,不过它包含 了实体间的关系


    ***(2)NSManagedObjectContext(被管理的对象上下文)


         操作实际内容


        作用:插入数据  查询  更新  删除


  3NSPersistentStoreCoordinator(持久化存储助理)


          相当于数据库的连接器


    (4)NSFetchRequest(获取数据的请求)


        相当于查询语句


     (5)NSPredicate(相当于查询条件)


    (6)NSEntityDescription(实体结构)


    (7)后缀名为.xcdatamodel的包


        里面的.xcdatamodel文件,用数据模型编辑器编辑


       

       

## .h文件


#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>



@interface ZWCoreDataManager : NSObject


/**

 *  CoreDataManager单例方法

 *

 *  @return 

 */

+(ZWCoreDataManager *)shareCoreDataManager;



//  管理对象上下文(数据管理器) ^^^^^

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;


// 数据模型器(表格)

@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;


// 数据连接器

@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;



// 保存上下文

- (void)saveContext;


/**

 *  获取沙盒路径

 *

 *  @return 沙盒路径的URL 

 */

- (NSURL *)applicationDocumentsDirectory;



## .m文件

#import "ZWCoreDataManager.h"


#define kCoreDataName @"CoreDataFirst"


@implementation ZWCoreDataManager



#pragma mark - Core Data stack


@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;



//单例方法

+(ZWCoreDataManager *)shareCoreDataManager {

    

    static ZWCoreDataManager *manager = nil;

    

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        

        manager = [[ZWCoreDataManager alloc] init];

        

    });

    

    return manager;

    

}



// 7.获取沙盒路径的URL(普通的实例化方法)

- (NSURL *)applicationDocumentsDirectory {

    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.MoNa.CoreDataFirst" in the application's documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}



//懒加载

- (NSManagedObjectModel *)managedObjectModel {

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    

    // 5. 获取CoreDatea.xcdatamodeld编译后的文件路径的URL

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:kCoreDataName withExtension:@"momd"];

    

    // ManagedObjectModel的创建

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}



// 3. 连接器的get方法 (懒加载)

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    // Create the coordinator and store

    

    //4.创建连接器

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    

    //6.创建数据库的路径

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataFirst.sqlite"];

    NSError *error = nil;

    NSString *failureReason = @"There was an error creating or loading the application's saved data.";

    

    

    // 8.设置连接器

    // 参数1:数据存储的类型

    // 参数3: 数据库的路径的URL

    // 参数4: 对连接器的一些设置(字典)

    // 参数5: 错误的信息

    

    

    // 数据更新字段

      NSDictionary * options =@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES};

    

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        abort();

    }

    

    return _persistentStoreCoordinator;

}



//1.管理对象上下文德get方法

//懒加载

- (NSManagedObjectContext *)managedObjectContext {

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    // 2. 调用连接器的get方法

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator) {

        return nil;

    }

    

    //数据管理器创建需要一个线程枚举

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

    

    //设置数据管理器的链接器

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;

}


#pragma mark - Core Data Saving support



// 改动后,保存时调用

- (void)saveContext {

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            abort();

        }

    }

}




@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值