iOS開發數據持久化之-CoreData

CoreData使用了面向對象的方式來操作數據,負責在數據庫中存儲數據.它的底層就是使用類似于SQL的技術來實現的.CoreData提供了一種簡便的對象持久化管理方式,讓我們可以不關心數據的存儲,只需關心對象的增加,刪除,更改,讀寫就好了.

CoreData介紹

  1. CoreData是蘋果公司封裝的數據持久化框架,在iOS3.0中開始開放.
  2. 它允許用戶按照實體-屬性-值模型組織數據,并以二級制,XML或者sqlite數據文件的格式進行持久化

優點

  1. 它是蘋果公司原生態的產品.
  2. 它可以節省代碼量,大概是30%~70%
  3. 它支持可視化建模
  4. CoreData支持數據庫版本升級

構成

我們在創建工程的時候,勾選Use Core Data選項,系統就會在AppDelegate自動幫我們生成包含CoreData的屬性和方法.并且生成一個test.xcdatamodeld的文件.

Use Core Data

在AppDelegate文件中

APPDelegate.h

上面圖片是系統自動幫我們生成的屬性和方法代碼.它們的作用分別是:

三個屬性:

1.managedObjectContext,是被管理的數據上下文.它被用來操作實際的內容,進行插入,查詢,刪除數據.
2.managedObjectModel,它是一個被管理的數據模型.可以簡單的理解為可視化建模文件,我們在可視化建模中是Entity自動生成Model,就是這個對象,方便讓文件存儲助理來進行管理.
3.persistentStoreCoordinator,這是一個持久化的存儲助理.它是CoreData的核心,他負責連接所有的模塊,包括真實的存儲文件.

兩個方法:
1.saveContext,它的作用就是將我們在內存中的數據進行持久化.
2.applicationDocumentsDirectory,這個方法是用來獲取真實文件的路徑的.

使用CoreData

這是使用一個簡單的例子,對CoreData的增,刪,改,查的使用進行說明.

創建Entity

我們使用CoreData實現數據在tableView上的展示(查),添加(增),刪除(刪),點擊更改(改).

UI界面

在storyboard中創建一個UITableViewController,把它放在NavgationController中,設置一個右按鈕.為其關聯方法,并且指定其為 initial View Controller.創建類文件,并進行關聯,設置cell的樣式為Subtitle.
在這里不詳細贅述,如果想要了解可以移步[http://www.lxweimin.com/p/872b84d982ae]

UI界面搭建,簡單演示

創建文件

選中.xcdatamodeld文件,按照上面的步驟創建一個Person實例,點擊任務欄的Editor按鈕,選擇下圖紅框中的選項創建文件.

創建Person文件

因為我們創建工程的時候,系統已經為我們在AppDelegate生成了一些屬性和方法.我們只需要在tableView中引入APPDelegate的頭文件就好了.

代碼
屬性

聲明兩個屬性,一個是上下文對象,我們使用它來處理所有關于存儲的相關請求.另外一個就是數據源啦,用來在tableView上展示的數據.

既然聲明了屬性,我們就需要在為他們初始化,我們在ViewDidLoad方法中為其初始化,因為我們的managedObjectContext是來自與AppDelegate,所以選擇下面的初始化方法.

    // 進行數據初始化
    AppDelegate *dele = [UIApplication sharedApplication].delegate;
    self.myContext = dele.managedObjectContext;
    
    self.allData = [NSMutableArray array];
    
    // 通過CoreData讀取本地所有的數據
    [self getAllDataFromCoreData];

點擊添加按鈕添加數據

// 添加數據
- (IBAction)addAction:(UIBarButtonItem *)sender {
    
    // 創建student對象
    // 創建一個實體描述對象
    NSEntityDescription *stuDis = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext];
    Student *stu = [[Student alloc]initWithEntity:stuDis insertIntoManagedObjectContext:self.myContext];
    // 給屬性賦值
    stu.name = @"張三";
    stu.age = arc4random() % 73 + 1;
    
    // 更新數據源
    [self.allData addObject:stu];
    // 修改界面
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.allData.count - 1 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    // 將數據保存到文件中進行持久化
    NSError *error = nil;
    [self.myContext save:&error];
    
    if (nil != error) {
        NSLog(@"數據庫持久化,存在問題");
    }
    [((AppDelegate *)[UIApplication sharedApplication].delegate) saveContext];
}

從數據庫查詢數據

- (void)getAllDataFromCoreData {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext];
    [fetchRequest setEntity:entity];
    // 排序條件
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.myContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"兩手空空,你讓我如何盆滿缽滿");
    }
    // 將查詢到的數據添加到數據源
    [self.allData addObjectsFromArray:fetchedObjects];
    // 從新加載tableView
    [self.tableView reloadData];
}

點擊cell改變數據

// 點擊cell的響應事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 先查詢
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext];
    [fetchRequest setEntity:entity];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.myContext executeFetchRequest:fetchRequest error:&error];
    Student *stu = self.allData[indexPath.row];
    stu.name = @"尼古拉斯-趙四";
    stu.age = 15;
    // 更新數據源
    [self.allData removeAllObjects];
    [self.allData addObjectsFromArray:fetchedObjects];
    // 刷新UI
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    // 將修改本地持久化
    [self.myContext save:nil];
}

設置編輯時間 右滑刪除

// 當點擊tableViewCell的刪除按鈕的時候回調用(提交編輯請求的時候)
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

        // 獲取當前cell代表的數據
        Student *stu = self.allData[indexPath.row];
        // 更新數據源
        [self.allData removeObject:stu];
        // 更新UI
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        // 將臨時數據庫里進行刪除并進行本地持久化
        [self.myContext deleteObject:stu];
        [self.myContext save:nil];
      
}

其他的方法,設置分區數,行數,以及cell

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.allData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"main_cell" forIndexPath:indexPath];
    
    Student *stu = self.allData[indexPath.row];
    
    cell.textLabel.text = stu.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",stu.age];
    
    return cell;
}

最后的效果

效果
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.CoreData 1.1 CoreData概述 1)Core data 是數據持久存儲的最佳方式 2)Core...
    微春風閱讀 3,858評論 0 10
  • 在程序開發中,數據層永遠是程序的核心結構之一。我們將現實事物進行抽象,使之變成一個個數據。對這些數據的加工處理是代...
    帥不過oneS閱讀 624評論 0 1
  • 在程序開發中,數據層永遠是程序的核心結構之一。我們將現實事物進行抽象,使之變成一個個數據。對這些數據的加工處理是代...
    sindri的小巢閱讀 16,850評論 13 85
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 說到吃Pizza,你的腦海中是否只會浮現Pizzahut必勝客的身影?如果是這樣,那今天的這期餐廳推薦將會讓你在P...
    港漂圈豆豆閱讀 539評論 1 4