Core Data 是iOS SDK里的一個(gè)很強(qiáng)大的框架,允許程序員以面向?qū)ο蟮姆绞絻?chǔ)存和管理數(shù)據(jù).使用Core Data框架,可以很輕松有效的通過面向?qū)ο蟮慕涌诠芾頂?shù)據(jù)
Core Data框架提供了對(duì)象-關(guān)系映射(ORM)的功能,即能夠?qū)C對(duì)象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite3數(shù)據(jù)庫文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對(duì)象
和SQLite的區(qū)別:Core Data不支持SQL語句
Core Data是對(duì)SQLite3的封裝,底層還是SQL語句,在數(shù)據(jù)操作過程中,將數(shù)據(jù)關(guān)系映射成對(duì)象,直接操作對(duì)象
SQL數(shù)據(jù)庫中的三個(gè)核心元素:表、字段大莫、記錄(一條數(shù)據(jù))
Core Data中與表對(duì)應(yīng)的叫做實(shí)體(Entity),實(shí)體在模型文件(DataModel)中設(shè)置數(shù)據(jù)的映射關(guān)系
Core Data中與字段對(duì)應(yīng)的是屬性(Attribute),屬性在實(shí)體中設(shè)置
Core Data中與記錄對(duì)應(yīng)的是對(duì)象(基類NSManagedObject),對(duì)象根據(jù)實(shí)體生成,CoreData通過操作對(duì)象進(jìn)行數(shù)據(jù)存儲(chǔ)
創(chuàng)建工程時(shí),直接勾選Use Core Data,這樣創(chuàng)建工程時(shí)自動(dòng)集成了Core Data
與普通創(chuàng)建工程的區(qū)別在于,勾選Use Core Data創(chuàng)建好的工程,會(huì)多出一個(gè)文件:
工程名.xcdatamodeld
點(diǎn)擊下面的Add Entity,創(chuàng)建實(shí)體
添加Entity(創(chuàng)建表)
添加Attributes(添加字段)
并且在Appdelegate中,也默認(rèn)幫我們實(shí)現(xiàn)了部分功能:
.h中
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
// 數(shù)據(jù)上下文 直接負(fù)責(zé)數(shù)據(jù)的增刪改查
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
// 數(shù)據(jù)模型 對(duì)應(yīng)的數(shù)據(jù)模型文件(.xcdatamodeld)
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
// 持久化存儲(chǔ)協(xié)調(diào)器
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// 保存上下文 增刪改查后,必須保存上下文,持久化協(xié)調(diào)器才會(huì)將數(shù)據(jù)和數(shù)據(jù)庫同步
- (void)saveContext;
// 沙盒Documents路徑 CoreData生成的數(shù)據(jù)庫默認(rèn)就在Documents中
- (NSURL *)applicationDocumentsDirectory;
@end
.m中
#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 "---ShenYJ---._1_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:@"_1_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:@"_1_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();
}
}
}