IOS開發之--Core Data的使用

來源:互聯網
上載者:User

標籤:

Core Data基礎知識

官方的說法是:Core Data is a schema-driven object graph management and persistence framework.

翻譯過來的意思大概是:Core Data是一個模式驅動的對象圖管理和持久化架構。

好吧,上面的字面意思不是很容易理解,那麼我們從以下幾個方面來協助那些有其餘開發經驗的程式員樹立一些觀念:

 

  1. Core Data不是一個資料庫,但是他可能使用一個資料庫。預設情況下,Core Data將使用SQLite,但是你可以完全不用關心任何關係型資料庫相關知識,或者SQL語句;
  2. Core Data不是一個類似於Hibernate的對象關係映射架構。Core Data僅僅是一個對象間的關聯式模式,使用者無需資料庫知識,並且資料也不一定儲存在資料庫中;
  3. Core Data允許你去儲存模型對象到檔案中並且可以在需要的時候取回資料,這一系列操作類似於打包和序列化操作,但是Core Data能夠做的更多;

 

Core Data能夠做的比較強大的功能包括:

 

  1. Core Data提供了維護模型對象變化的基礎能力,這樣你可以執行撤銷和重做操作,並且Core Data可以維護對象間的相互關係;
  2. Core Data允許你在給定時間內在記憶體中保留模型對象的一個子集,這對於嚴苛的iOS記憶體環境相當重要;
  3. 使用Schema來描述模型對象。你可以在一個圖形化的編輯器中定義你的模型的主要特性,甚至可以包含各個對象間的關係。這樣提供了一個簡單的手段來保證一個基本的健壯性,例如可以設定預設值和屬性值的驗證;
  4. 允許你維護對象的不想交集合。例如,允許你在一個視圖中對對象進行編輯,但這個內容可能被丟棄,導致另一個視圖中不更新對象;
  5. 對對象的版本管理操作提供支援,這樣可以很方便的將舊版對象升級為新版對象;

 

Core Data不是一個單獨的類,而是一群需要互相協作的類的集合。整個Core Data的架構圖是比較複雜的:

 

執行個體

MyCoreData

 

    1. 建立一個新的Empty工程,名字叫MyCoreData,工程屬性選擇Core Data和ARC支援;
    2. 在繼續下一步之前,我們瞭解幾個內容:

      • Managed Object Model,描述了你將在App中使用的Schema。如果你有資料庫背景知識,你可以想象一下資料庫的Schema。這裡的Schema實際上指的是一個對象(或者說實體)的集合。在XCode中,模型被儲存在.xcdatamodeld檔案中。你可以使用可視化的編輯器來定義實體、屬性、關係等;
      • Persistent Store Coordinator,在iOS中預設使用SQLite儲存持久化資料,當然Core Data提供了儲存不同實體到不同儲存物件的手段。PSC就是對儲存手段進行維護的管理器。當然你完全可以忘記這個對象,因為你基本上不需要和他直接互動;
      • Managed Object Context,這個對象用於管理對象的序列化和還原序列化工作,也是在使用Core Data Stack時主要使用的工具;
      • 整理下可以發現,從底層往上的順序分別是:DataStore->Persistent Object Store->Persistent Store Coordinator->Managed Object Context->App;
    3. 基本概念講完了,我們點擊項目產生的.xcdatamodel檔案,點擊Add Entity,添加一個實體,名字叫Novel;


    4. 添加屬性,定義如下的三個屬性值:


    5. 建立使用者介面,在File->New中建立一個StoryBoard,然後在Project屬性中設定為這個Story Board;
    6. 在AppDelegate.m檔案中,將自動產生的didFinishLaunchingWithOptions方法的實現清空,變為:
      [cpp] view plaincopy
      1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
      2. {  
      3.     return YES;  
      4. }  
    7. 在Story Board編輯介面中,添加一個Table View Controller、一個View Controller,設定Table View Controller跳轉到View Controller(注意選擇Segue的Modal,因為後面使用dismissViewController來釋放Details視窗),並且Embed in到Navigator View Controller;
    8. 在Table View Controller中添加一個Button,並且選擇Button的Identifier為Add,使之變成一個加號按鈕;
    9. 選擇Table View的Cell,將其Style修改為Right Detail;
    10. 去那個名為Details的View Controller,先放置一個Navigation Bar到介面上面,然後拖動兩個Button到Navigation Bar上面,並且分別設定對應的Bar Button Item的Identifier屬性為Cancel和Save,如下:
    11. 在Details介面中添加三個text field,並且分別設定他們的placeholder屬性為:name、author、version;
    12. ListView上面的那個加號按鈕在點擊時需要跳轉到Details介面,所以需要在Story Board上選擇這個按鈕,按住Control鍵,拖動到Details這個View之上後釋放滑鼠,選擇Segue->Modal;
    13. 在原始碼檔案夾中建立一個Object-C類,命名為NovelListViewController,父類選擇UITableViewController;
    14. 在Story Board中,將Table View的Class設定為NovelListViewController;
    15. 同樣,設定Details這個View的Class為建立立的NovelDetailsViewController;
    16. 在NovelDetailsViewController中產生和介面中的TextField對應的控制項變數及回應程式法:
      [cpp] view plaincopy
      1. #import <UIKit/UIKit.h>  
      2.   
      3. @interface NovelDetailsViewController : UIViewController  
      4. @property (strong, nonatomic) IBOutlet UITextField *tfName;  
      5. @property (strong, nonatomic) IBOutlet UITextField *tfAuthor;  
      6. @property (strong, nonatomic) IBOutlet UITextField *tfVersion;  
      7.   
      8. - (IBAction)cancel:(id)sender;  
      9. - (IBAction)save:(id)sender;  
      10. @end  
    17. 接下來進入正題,我們將進入操作Core Data的階段。我們將要實現的主要功能包括:在Details頁面中儲存資料,在List頁面中將資料取回;
    18. 在NovelDetailsViewController.m中加入代碼:
      [cpp] view plaincopy
      1. - (NSManagedObjectContext *)managedObjectContext {  
      2.     NSManagedObjectContext *context = nil;  
      3.     id delegate = [[UIApplication sharedApplication] delegate];  
      4.     if ([delegate performSelector:@selector(managedObjectContext)]) {  
      5.         context = [delegate managedObjectContext];  
      6.     }  
      7.     return context;  
      8. }  
    19. 記得我們當時對工程添加Core Data支援的時候,我們的AppDelegate中自動添加了一個Managed Object Context,我們將使用這個Context來儲存或者取回對象;
    20. 我們將兩個按鈕的事件處理方法變為:
      [cpp] view plaincopy
      1. - (IBAction)cancel:(id)sender {  
      2.     [self dismissViewControllerAnimated:YES completion:nil];  
      3. }  
      4.   
      5. - (IBAction)save:(id)sender {  
      6.     // get Managed Object Context  
      7.     NSManagedObjectContext *context = [self managedObjectContext];  
      8.       
      9.     // Create a new managed object  
      10.     NSManagedObject *newNovel = [NSEntityDescription insertNewObjectForEntityForName:@"Novel" inManagedObjectContext:context];  
      11.     [newNovel setValue:self.tfName.text forKey:@"name"];  
      12.     [newNovel setValue:self.tfAuthor.text forKey:@"author"];  
      13.     [newNovel setValue:self.tfVersion.text forKey:@"version"];  
      14.       
      15.     NSError *error = nil;  
      16.     // Save the object to persistent store  
      17.     if (![context save:&error]) {  
      18.         NSLog(@"Can‘t Save! %@ %@", error, [error localizedDescription]);  
      19.     }  
      20.       
      21.     [self dismissViewControllerAnimated:YES completion:nil];  
      22. }  
      當點擊Cancel按鈕的時候,我們使用一個動畫方式將Details視窗關閉掉。
      當點擊Save按鈕的時候,我們首先擷取Context,然後建立一個新的Managed Object,設定novel的屬性,接著調用context的save來儲存資料,最後關閉介面。
    21. 現在我們看如何擷取列表。我們在TableViewController中添加一個數組用來儲存Novel的列表:
      [cpp] view plaincopy
      1. #import <UIKit/UIKit.h>  
      2.   
      3. @interface NovelListViewController : UITableViewController  
      4.   
      5. @property(strong, nonatomic) NSMutableArray *novelList;  
      6.   
      7. @end  
    22. 同樣對於List頁面需要添加擷取Context和載入時擷取數組元素列表介面:
      [cpp] view plaincopy
      1. @implementation NovelListViewController  
      2.   
      3. @synthesize novelList;  
      4.   
      5. - (NSManagedObjectContext *)managedObjectContext  
      6. {  
      7.     NSManagedObjectContext *context = nil;  
      8.     id delegate = [[UIApplication sharedApplication] delegate];  
      9.     if ([delegate performSelector:@selector(managedObjectContext)]) {  
      10.         context = [delegate managedObjectContext];  
      11.     }  
      12.     return context;  
      13. }  
      14.   
      15. - (void)viewDidAppear:(BOOL)animated  
      16. {  
      17.     [super viewDidAppear:animated];  
      18.       
      19.     // Fetch the devices from persistent data store  
      20.     NSManagedObjectContext *managedObjectContext = [self managedObjectContext];  
      21.     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Novel"];  
      22.     self.novelList = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];  
      23.       
      24.     [self.tableView reloadData];  
      25. }  
    23. 接下來改造List介面的表格顯示模組:
      [cpp] view plaincopy
      1. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
      2. {  
      3. #warning Potentially incomplete method implementation.  
      4.     // Return the number of sections.  
      5.     return 1;  
      6. }  
      7.   
      8. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
      9. {  
      10. #warning Incomplete method implementation.  
      11.     // Return the number of rows in the section.  
      12.     return self.novelList.count;  
      13. }  
      14.   
      15. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
      16. {  
      17.     static NSString *CellIdentifier = @"Cell";  
      18.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];  
      19.       
      20.     // Configure the cell...  
      21.     NSManagedObject *device = [self.novelList objectAtIndex:indexPath.row];  
      22.     [cell.textLabel setText:[NSString stringWithFormat:@"%@ %@", [device valueForKey:@"name"], [device valueForKey:@"version"]]];  
      23.     [cell.detailTextLabel setText:[device valueForKey:@"author"]];  
      24.       
      25.     return cell;  
      26. }  
      注意在Story Board中設定Table View Cell的Identifier屬性值為Cell,與代碼中的保持一致。
    24. 至此,程式功能全部完成,查看探索資料能夠正常儲存,但我們沒有寫一行和資料庫相關的代碼。

IOS開發之--Core Data的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.