IOS 資料存放區之 Core Data詳解,ioscore

來源:互聯網
上載者:User

IOS 資料存放區之 Core Data詳解,ioscore

  Core Date是ios3.0後引入的資料持久化解決方案,它是是蘋果官方推薦使用的,不需要藉助第三方架構。Core Date實際上是對SQLite的封裝,提供了更進階的持久化方式。在對資料庫操作時,不需要使用sql語句,也就意味著即使不懂sql語句,也可以操作資料庫中的資料。

  在各類應用開發中使用資料庫操作時通常都會用到 (ORM) “對象關係映射”,Core Data就是這樣的一種模式。ORM是將關聯式資料庫中的表,轉化為程式中的對象,但實際上是對資料中的資料進行操作。

  在使用Core Data進⾏行資料庫存取並不需要手動建立資料庫,建立資料庫的過程完全由Core Data架構自動完成,開發人員需要做的就是把模型建立起來,具體資料庫的建立不需要管。簡單點說,Core Data實際上是將資料庫的建立、表的建立、對象和表的轉換等操作封裝起來,極大的簡化了我們的操作。

  Core Date與SQLite相比較,SQLite比較原始,操作比較複雜,使用的是C的函數對資料庫進行操作,但是SQLite可控性更強,並且能夠跨平台。

  下面,讓我們一起來學習一下Core Data的簡單使用。

一、使用Core Data,添加實體和模型

  在建立項目的時候可以選擇使用Core Data,項目建立成功後,會在AppDelegate類中自動添加相關代碼,此外,還會自動產生一個資料模型檔案JRCoreData.xcdatamodeld

 

AppDelegate.h

//  AppDelegate.h//  JRCoreData////  Created by jerei on 15-6-24.//  Copyright (c) 2015年 jerehedu. All rights reserved.//#import <UIKit/UIKit.h>#import <CoreData/CoreData.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;@end

AppDelegate.m

//  AppDelegate.m//  JRCoreData////  Created by jerei on 15-6-24.//  Copyright (c) 2015年 jerehedu. All rights reserved.//#import "AppDelegate.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.    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.jerehedu.JRCoreData" 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:@"JRCoreData" withExtension:@"momd"];    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    return _managedObjectModel;}- (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:@"JRCoreData.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] 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

  如果項目在建立的時候沒有選擇使用Core Data,但是在後面需要使用,那麼需要手動的添加AppDelegate中的相關代碼。此外,還需要手動添加一個Data Model檔案

 

  建立Data Model檔案時需要注意,檔案名稱要與AppDelegate.m中managedObjectModel方法中提到的檔案名稱相匹配。

  有了Data Model檔案後,就可以在裡面添加實體和關係,實際上就是向資料庫中添加表格和建立表格之間的關聯。添加實體:

 

  每個學生有一個所在的班級,每個班級中有多個學生,因此,學生和班級之間可以建立關係。建立關係:

 

  建立關係之後,可以切換顯示的樣式,以圖表的方式查看實體之間的關係,:

 

  完成上述步驟,資料庫中表格的建立就已經完成,和使用SQLite比較,省略了sql語句以及調用C函數操作資料庫的步驟,另外,在建立實體的時候不需要設定主鍵,實體物件的屬性的類型是OC的類型,實體中其他實體物件類型是通過建立關係添加的。

  建立好實體後,可以通過添加NSManagedObject subclass檔案,系統可以自動添加實體對應的資料模型類,:

 

二、通過代碼實現資料庫的操作

  1、 向學生表中插入一條資料

  在使用Core Data的時候,AppDelegate中添加了NSManagedObjectContext對象,需要獲得這個管理對象的上下文來進行操作。在操作的過程中,需要得到NSManagedObject實體,然後通過kvc設定實體的屬性值,最後通過上下文調用save方法儲存資料。

- (void)insert {        AppDelegate *delegate = [[UIApplication sharedApplication] delegate];        //1. 獲得context    NSManagedObjectContext *context = delegate.managedObjectContext;    //2. 找到實體結構,並產生一個實體物件    /*     NSEntityDescription實體描述,也就是表的結構     參數1:表名字     參數2:執行個體化的對象由誰來管理,就是context     */    NSManagedObject *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];        NSManagedObject *class1 = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:context];    [class1 setValue:[NSNumber numberWithInt:1] forKey:@"c_id"];    [class1 setValue:@"一班" forKey:@"c_name"];        //3. 設定實體屬性值    [stu setValue:[NSNumber numberWithInt:1] forKey:@"s_id"];    [stu setValue:@"jerehedu" forKey:@"s_name"];    [stu setValue:class1 forKey:@"s_class"];        //4. 調用context,儲存實體,如果沒有成功,返回錯誤資訊    NSError *error;    if ([context save:&error]) {        NSLog(@"save ok");    }    else    {        NSLog(@"%@",error);    }}

  2、查詢學生表中全部資料

  查詢與插入資料操作類似,但是多了構造查詢對象的步驟,查詢得到結果集是一個數組,遍曆數組,可以取出查詢資料。

- (void)selectAll {    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];        NSManagedObjectContext *context = delegate.managedObjectContext;        NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];        //構造查詢對象    NSFetchRequest *request = [[NSFetchRequest alloc] init];    [request setEntity:stu];        //執行查詢,返回結果集    NSArray *resultAry = [context executeFetchRequest:request error:nil];        //遍曆結果集    for (NSManagedObject *enity in resultAry) {        NSLog(@"id=%i name=%@ class=%@",[[enity valueForKey:@"s_id"] intValue],[enity valueForKey:@"s_name"],[[enity valueForKey:@"s_class"] valueForKey:@"c_name"]);    }}

  3、查詢指定條件的學生資訊,並更新

  指定條件的查詢除了需要構造查詢對象,還需要把查詢的條件用謂詞表示。然後遍曆查詢結果數組中的資料,進行更行,並儲存。

- (void)update{    //    更新 (從資料庫找到-->更新)    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];    NSManagedObjectContext *context = delegate.managedObjectContext;        NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];        NSFetchRequest *request = [NSFetchRequest new];    [request setEntity:stu];        //構造查詢條件,相當於where子句    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"s_id=%i",1];        //把查詢條件放進去    [request setPredicate:predicate];        //執行查詢    NSArray *studentAry = [context executeFetchRequest:request error:nil];    if (studentAry.count>0)    {        //更新裡面的值        NSManagedObject *obj = studentAry[0];        [obj setValue:@"apple" forKey:@"s_name"];    }    [context save:nil];        //顯示    [self selectAll];}

  4、刪除指定條件的學生資訊

  刪除之前首先需要根據條件進行查詢,查詢到資料後刪除,並儲存。

- (void)delete{    //刪除 先找到,然後刪除    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];    NSManagedObjectContext *context = delegate.managedObjectContext;        NSEntityDescription *stu = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];        NSFetchRequest *request = [NSFetchRequest new];    [request setEntity:stu];        //構造查詢條件,相當於where子句    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"s_id=%i",1];        //把查詢條件放進去    [request setPredicate:predicate];    //執行查詢    NSManagedObject *obj = [[context executeFetchRequest:request error:nil] lastObject];    //刪除    if (obj) {        [context deleteObject:obj];        [context save:nil];    }        [self selectAll];}
三、小結

  Core Data是蘋果官方推薦使用的資料持久化方式,在使用的過程中,不需要匯入資料庫架構,也不需要使用sql語句操作資料庫,完全是按照物件導向的思想,使用實體模型來操作資料庫。在使用的過程中需要注意的是,如果模型發生了變化,可以選擇重建實體類檔案,但是自動產生的資料庫並不會自動更新,需要考慮重建資料庫,並把之前資料庫中資料進行移植。Core Data能夠簡化操作,但是它不支援跨平台使用,如果想實現跨平台,就需要使用SQLite來進行資料持久化。

 

  疑問諮詢或技術交流,請加入官方QQ群: (452379712)

 

作者:傑瑞教育
出處:http://www.cnblogs.com/jerehedu/ 
本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.