CoreData使用了面向對象的方式來操作數據,負責在數據庫中存儲數據.它的底層就是使用類似于SQL的技術來實現的.CoreData提供了一種簡便的對象持久化管理方式,讓我們可以不關心數據的存儲,只需關心對象的增加,刪除,更改,讀寫就好了.
CoreData介紹
- CoreData是蘋果公司封裝的數據持久化框架,在iOS3.0中開始開放.
- 它允許用戶按照實體-屬性-值模型組織數據,并以二級制,XML或者sqlite數據文件的格式進行持久化
優點
- 它是蘋果公司原生態的產品.
- 它可以節省代碼量,大概是30%~70%
- 它支持可視化建模
- CoreData支持數據庫版本升級
構成
我們在創建工程的時候,勾選Use Core Data選項,系統就會在AppDelegate自動幫我們生成包含CoreData的屬性和方法.并且生成一個test.xcdatamodeld的文件.
在AppDelegate文件中
上面圖片是系統自動幫我們生成的屬性和方法代碼.它們的作用分別是:
三個屬性:
1.managedObjectContext,是被管理的數據上下文.它被用來操作實際的內容,進行插入,查詢,刪除數據.
2.managedObjectModel,它是一個被管理的數據模型.可以簡單的理解為可視化建模文件,我們在可視化建模中是Entity自動生成Model,就是這個對象,方便讓文件存儲助理來進行管理.
3.persistentStoreCoordinator,這是一個持久化的存儲助理.它是CoreData的核心,他負責連接所有的模塊,包括真實的存儲文件.
兩個方法:
1.saveContext,它的作用就是將我們在內存中的數據進行持久化.
2.applicationDocumentsDirectory,這個方法是用來獲取真實文件的路徑的.
使用CoreData
這是使用一個簡單的例子,對CoreData的增,刪,改,查的使用進行說明.
我們使用CoreData實現數據在tableView上的展示(查),添加(增),刪除(刪),點擊更改(改).
UI界面
在storyboard中創建一個UITableViewController,把它放在NavgationController中,設置一個右按鈕.為其關聯方法,并且指定其為 initial View Controller.創建類文件,并進行關聯,設置cell的樣式為Subtitle.
在這里不詳細贅述,如果想要了解可以移步[http://www.lxweimin.com/p/872b84d982ae]
創建文件
選中.xcdatamodeld文件,按照上面的步驟創建一個Person實例,點擊任務欄的Editor按鈕,選擇下圖紅框中的選項創建文件.
因為我們創建工程的時候,系統已經為我們在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;
}