1.Core Data 是数据持久化存储的最佳方式
2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型
在Mac OS X 10.5Leopard及以后的版本中,开发者也可以通过继承NSPersistentStore类以创建自定义的存储格式
3.好处:能够合理管理内存,避免使用sql的麻烦,高效
4.构成:
(1)NSManagedObjectContext(被管理的数据上下文)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据
(2)NSManagedObjectModel(被管理的数据模型)
数据库所有表格或数据结构,包含各实体的定义信息
作用:添加实体的属性,建立属性之间的关系
操作方法:视图编辑器,或代码
(3)NSPersistentStoreCoordinator(持久化存储助理)
相当于数据库的连接器
作用:设置数据存储的名字,位置,存储方式,和存储时机
(4)NSManagedObject(被管理的数据记录)
相当于数据库中的表格记录
(5)NSFetchRequest(获取数据的请求)
相当于查询语句
(6)NSEntityDescription(实体结构)
相当于表格结构
我们用图简单地描述下它的作用:
在Core Data,需要进行映射的对象称为实体(entity),而且需要使用Core Data的模型文件来描述app中的所有实体和实体属性。这里以Person(人)和Card(身份证)2个实体为例子,先看看实体属性和实体之间的关联关系:
Person实体中有:name(姓名)、age(年龄)、card(身份证)三个属性
Card实体中有:no(号码)、person(人)两个属性
接下来看看创建模型文件的过程:
1.选择模板,创建新工程
打开AppDelegate.m 文件 你会发现工程中已经有以下封装好的代码
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (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.
[self saveContext];
}
#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.CoreData" 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;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
#pragma mark ---- 存储助手 中介 取出数据放到内存 连接数据库的中介
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil 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;
}
#pragma mark ---- 1.管理对象的上下文,持久化存储模型对象
- (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;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_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
在模型里添加实体
添加Person的2个基本属性
添加Card的1个基本属性
建立Person和Card的关联关系
建立Card和Person的关联关系
创建NSManagedObject的子类
默认情况下,利用Core Data取出的实体都是NSManagedObject类型的,能够利用键-值对来存取数据。但是一般情况下,实体在存取数据的基础上,有时还需要添加一些业务方法来完成一些其他任务,那么就必须创建NSManagedObject的子类
工程中自动生成的 model 模型
数据库的操作无非是增删改查:代码段如下 仅供参考
补充导入::#import "AppDelegate.h"
@interface ViewController ()
@property(nonatomic,strong)NSManagedObjectContext *context;//上下文
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//通过 delegate 获取上下文
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
_context = delegate.managedObjectContext;
//下面四个方法,需要哪个调用哪个
[self insert];//数据库插入数据
//[self fetch];//查询数据
//[self Update];//修改数据
//[self dele];//数据库删除数据
}
-(void)insert{
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person.name = @"王宝";
//插入
NSError *error;
[self.context save:&error];
if (error) {
NSLog(@"保存失败, error = %@",[error
localizedDescription]);
}else{
NSLog(@"成功");
}
}
-(void)dele{
NSFetchRequest *request = [[NSFetchRequest alloc]init];//创建查询对象
[request setFetchLimit:10];//相当于每页展示多少数据
[request setFetchOffset:0];//数据偏移量 相当于页数
//创建需要查询的实体
NSEntityDescription *enity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
[request setEntity:enity];
//执行查询
NSArray *fetchResult = [self.context executeFetchRequest:request error:nil];
if (fetchResult.count>0) {
Person *person = fetchResult[0];
NSLog(@"==%@", person.name);
NSError *saveError;
//保存
[self.context deleteObject:person];
[self.context save:&saveError];
if (saveError) {
NSLog(@"删除失败");
}else{
NSLog(@"删除成功");
[self fetch];
}
}
}
-(void)Update{
NSFetchRequest *request = [[NSFetchRequest alloc]init];//创建查询对象
[request setFetchLimit:10];//相当于每页展示多少数据
[request setFetchOffset:0];//数据偏移量 相当于页数
//创建需要查询的实体
NSEntityDescription *enity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
[request setEntity:enity];
//执行查询
NSArray *fetchResult = [self.context executeFetchRequest:request error:nil];
if (fetchResult.count>0) {
Person *person = fetchResult[0];
NSLog(@"==%@",person.name);
person.name = @"jiajia";
NSError *saveError;
//保存
[self.context save:&saveError];
if (saveError) {
NSLog(@"xxx");
}else{
NSLog(@"person.name %@",person.name);
}
}
}
-(void)fetch{
NSFetchRequest *request = [[NSFetchRequest alloc]init];//创建查询对象
[request setFetchLimit:10];//相当于每页展示多少数据
[request setFetchOffset:0];//数据偏移量 相当于页数
//创建需要查询的实体
NSEntityDescription *enity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
[request setEntity:enity];
//执行查询
NSArray *fetchResult = [self.context executeFetchRequest:request error:nil];
if (fetchResult.count>0) {
Person* person = fetchResult[0];
NSLog(@"==%@",person.name);
}else{
NSLog(@"没有数据");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end