- CoreData数据持久化框架是Cocoa API的一部分,首次在iOS5版本中出现,它允许按照实体-属性-值模式组织数据,并以XML,二进制文件或者SQLite数据文件的格式持久化数据.
- CoreData主要提供的对象-关系映射(ORM)功能,把OC对象转化为数据保存到文件,也可以数据转化为OC对象
CoreData和SQLite的比较
- SQLite
1 基于C接口,需要使用sql语句,代码繁琐
2 在处理大量数据时,表关系更直观
3 在OC中是不是可视化的 - CoreData
1 可视化,有undo/redo能力
2 可以实现多种文件格式 NSSQLiteStoreType,NSBinaryStoreType,NSInMemoryStore Type,NSXMLStoreType.
3.苹果官方API支持,与iOS结合更紧密
CoreData核心对象
- NSManagedObjectContext 数据管理器器类(负责应用和数据库之间的交互)
- NSManagedObjectModel 数据模型器类(当对于可视化创建model的基类)
- NSPersistentStoreCoordinator 数据协调器类 (添加持久化数据库)
- NSEntityDescription 实体描述类(用来描述实体类)
CoreData数据库框架的核心对象
- NSPersistentStore:持久化存储,一个被封装好的底层类,用于存储数据
- 存储文件:用来存储和管理数据的文件
1 NSSQLiteStoreType
2 NSBinaryStoreType
3 NSInMemoryStoreType
4 NSXMLStoreType. - NSManagedObjectContext:被管理对象上下文CoreData中用于操作和使用数据,负责应用和数据库之间的交互
1 数据的保存需要NSManagedObjectContext进行save操作
2 数据的查询需要NSManagedObjectContext进行executeFetchRequest操作(返回值是数组)
3 CoreData提供的是对象关系映射,NSManagedObjectContext操作的都是NSManagedObject对象 - NSManagedObjectMode:被管理对象对象模型,管理多个对象
- NSManagedObject:被管理对象,CoreData返回的数据模型,被管理的对象是根据实体描述生成的
- NSEntityDescription:实体描述类,根据实体创建被管理对象
- Entity:实体类,实体是对象文件数据的描述,被管理对象表示实体,实体包含名称,属性(字段)和关系,实体的名称通常和被管理对象名一致
- NSFetchRequest:查询请求,NSManagedObjectContext根据NSFetchRequest查询数据,以数组形式返回,数组中包含被管理对象(NSManagedObject)
- NSSortDescriptor:排序操作
CoreData数据库的简单操作
第一步:添加AppDelegate头文件
#import "AppDelegate.h"
第二步:通过单例方法获取协议
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
第三步:创建实体对象
//.创建实体对象(也就是具体对那个表进行操作)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:delegate.managedObjectContext];
第四步:增删查改
/**增**/
//在创建的时候要使用coreData提供的方法,这样数据管理器就可以管理此数据了
Person *person = [[Person alloc] initWithEntity:entity insertIntoManagedObjectContext:delegate.managedObjectContext];
//同步到数据库
person.name = @"张三";
person.sex = @"nan";
person.age = 12;
[delegate saveContext];
/**删**/
// 创建请求体
NSFetchRequest *request1 = [[NSFetchRequest alloc] init];
// //请求需要的具体实体
request1.entity = entity;
// //创建请求条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 1"];
request1.predicate = predicate;
NSArray *array1 = [delegate.managedObjectContext executeFetchRequest:request1 error:nil];
for (Person *person2 in array1) {
[delegate.managedObjectContext deleteObject:person2];
NSLog(@"%@",person2.name);
}
[delegate saveContext];
/**查**/
//创建请求体
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//请求体需要的具体实体
request.entity = entity;
NSArray *array = [delegate.managedObjectContext executeFetchRequest:request error:nil];
for (Person *person1 in array) {
NSLog(@"%@",person1.name);
NSLog(@"%p",person1);
}
/**改**/
//创建请求体
NSFetchRequest *request2 = [[NSFetchRequest alloc] init];
request2.entity = entity;
//创建请求条件
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name = %@",@"张三"];
request2.predicate = predicate1;
NSArray *array2 = [delegate.managedObjectContext executeFetchRequest:request2 error:nil];
for (Person *person3 in array2) {
person3.name = @"李四";
NSLog(@"%@",person3.name);
}
[delegate saveContext];
AppDelegate中CoreData自带的方法
<pre><code>- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "xalo.UI___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;
}
//获取文件目录路径,momd是xcdatamodeld的简写
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"UI___CoreData" withExtension:@"momd"];
_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
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UI___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:@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES} 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.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}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();
}
}
}