数据库-CoreData简介 - (Obj-C)

Core Data 是iOS SDK里的一个很强大的框架,允许程序员以面向对象的方式储存和管理数据.使用Core Data框架,可以很轻松有效的通过面向对象的接口管理数据

Core Data框架提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite3数据库文件中,也能够将保存在数据库中的数据还原成OC对象

和SQLite的区别:Core Data不支持SQL语句
Core Data是对SQLite3的封装,底层还是SQL语句,在数据操作过程中,将数据关系映射成对象,直接操作对象

SQL数据库中的三个核心元素:表、字段、记录(一条数据)
Core Data中与表对应的叫做实体(Entity),实体在模型文件(DataModel)中设置数据的映射关系
Core Data中与字段对应的是属性(Attribute),属性在实体中设置
Core Data中与记录对应的是对象(基类NSManagedObject),对象根据实体生成,CoreData通过操作对象进行数据存储

创建工程时,直接勾选Use Core Data,这样创建工程时自动集成了Core Data

数据库-CoreData简介 - (Obj-C)_第1张图片
CoreData_1.png

与普通创建工程的区别在于,勾选Use Core Data创建好的工程,会多出一个文件:

工程名.xcdatamodeld

CoreData_2.png

点击下面的Add Entity,创建实体
添加Entity(创建表)
添加Attributes(添加字段)

CoreData_3.png

并且在Appdelegate中,也默认帮我们实现了部分功能:
.h中

#import 
#import 

@interface AppDelegate : UIResponder 

@property (strong, nonatomic) UIWindow *window;
// 数据上下文  直接负责数据的增删改查
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
// 数据模型 对应的数据模型文件(.xcdatamodeld)
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
// 持久化存储协调器
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

// 保存上下文   增删改查后,必须保存上下文,持久化协调器才会将数据和数据库同步
- (void)saveContext;
// 沙盒Documents路径    CoreData生成的数据库默认就在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();
        }
    }
}

你可能感兴趣的:(数据库-CoreData简介 - (Obj-C))