Core Data數據持久化

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







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章