CoreData使用了面向對象的方式來操作資料,負責在資料庫中存儲資料.它的底層就是使用類似于SQL的技術來實作的.CoreData提供了一種簡便的對象持久化管理方式,讓我們可以不關心資料的存儲,隻需關心對象的增加,删除,更改,讀寫就好了.
CoreData介紹
- CoreData是蘋果公司封裝的資料持久化架構,在iOS3.0中開始開放.
- 它允許使用者按照實體-屬性-值模型組織資料,并以二級制,XML或者sqlite資料檔案的格式進行持久化
優點
- 它是蘋果公司原生态的産品.
- 它可以節省代碼量,大概是30%~70%
- 它支援可視化模組化
- 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.jianshu.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() % + ;
// 更新資料源
[self.allData addObject:stu];
// 修改界面
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.allData.count - inSection:];
[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 = ;
// 更新資料源
[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 ;
}
- (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;
}
最後的效果
效果