封装CoreData数据库将下面的代码块直接粘贴到工程即可
//封装CoreDataManager继承于<NSObject>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CoreDataManager : NSObject
//数据管理类(被管理的上下文) 对NSManagedObjectContext(实体管理类,相当于数据库中某张表的某行数据)进行增删改查
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
//数据管理模型 管理数据库中的各种表格
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
//数据连接器(持久化存储处理),实现从下层获取数据,向上层提供数据
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;//持久化存储
- (NSURL *)applicationDocumentsDirectory;//回去沙盒路径
+ (CoreDataManager *)shareManager;
@end
#import "CoreDataManager.h"
#define MANAGER_OBJECT_MODEL @"CoreData0920"
@implementation CoreDataManager
+ (CoreDataManager *)shareManager{
static CoreDataManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[CoreDataManager alloc]init];
});
return manager;
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.CoreData0920" 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;
}
//3.获取表结构 momd为数据库运行时的后缀
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:MANAGER_OBJECT_MODEL withExtension:@"momd"];//momd为数据库运行时的后缀
//4.创建数据模型器 包含表结构
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (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
//2.为空 创建数据连接器
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
//5.拼接存储路径
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",MANAGER_OBJECT_MODEL]];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
//6.数据连接器添加设置
//允许自动升级版本
NSDictionary *option = [NSDictionary dictionaryWithObject:@(YES) forKey:NSMigratePersistentStoresAutomaticallyOption];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:option 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;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
//懒加载 为空创建 不为空直接返回
//What is Lazy loading?--->用的时候就创建,不用的时候就不创建
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
//1.获取数据连接器
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
//7.创建数据管理器
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
//8.为数据管理器设置助理
[_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
讲上述代码直接粘贴即可
//在AppDelegate中找到
//程序意外退出
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
//程序意外停止时,存储数据库
[[CoreDataManager shareManager]saveContext];
}
接下来就可以直接调用了