• Core Data 是 iOS SDK 里的一个很强大的框架,允许程序员 以面向对象 的方式储存和管理数据 。使用 Core Data 框架,程序员可以很轻松有效 地通过面向对象的接口管理数据
•
Core Data
框架提供了
对象
-
关系映射
(ORM)
的功能,即能够将
OC
对象转 化成数据,保存在
SQLite3
数据库文件中,也能够将保存在数据库中的 数据还原成
OC
对象
•
在数据操作过程中,无需编写任何
SQL
语句
•
要使用
Core Data
,
需要导入
CoreData
框架
Core Data 主要对象
•
NSManagedObjectContext
:负责应用和数据库之间的交互
(CRUD)
•
NSPersistentStoreCoordinator
:添加持久化存储库(如
SQLite
数据 库),
是物理数据存储的物理文件和程序之间的联系的桥梁
,负责管 理
不同对象上下文
•
NSManagedObjectModel
:被管理的对象模型
三者关系 参考:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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 "nyhx.Core_Data" 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:@"Core_Data" 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:@"Core_Data.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; } - (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(); } } }
• NSEntityDescription :实体描述
新增记录(NSEntityDescription)
//_context--->NSManagedObjectContext
Person
*p = [
NSEntityDescription
insertNewObjectForEntityForName
:
@"Person"
inManagedObjectContext
:
_context
];
p.
name
=
@"
张三
"
; p.
age
=
@18
;
[
_context
save
:
nil
];
查询数据(NSFetchRequest)
NSFetchRequest
*request = [
NSFetchRequest
fetchRequestWithEntityName
:
@"Person"
];
request.
predicate
= [
NSPredicate
predicateWithFormat
:
@"%K LIKE '*52*' OR name CONTAINS '
三
'"
,
@"phoneNo"
];
NSArray
*array = [
_context
executeFetchRequest
:request
error
:
nil
];
删除数据
NSArray * mutablFetchResult = [_context executeFetchRequest:request error:&error];
for (User*user in mutableFetchResult) {
[_context deleteObject:user];
}
//判断是否删除成功
BOOL isDeleteSuccess = [_context save:&error];//保存(容易忘)
修改
NSArray * mutablFetchResult = [_context executeFetchRequest:request error:&error];
for (User*user in mutablFetchResult) {
[user setAge:[NSNumber numberWithInteger:999]];
}
//判断是否修改成功
BOOL isSaveSuccess = [_context save:&error];//保存(容易忘)
创建好实体后,可以通过添加NSManagedObject subclass文件,系统可以自动添加实体对应的数据模型类,如图所示: