上一篇文章我們從一個小例子講解了 Core Data 的使用方式。其實儘管概念很多,但實際應用時大多數情況下我們不需要接觸太多類和方法,只要拿到 context 並操作即可。
這次我們來看看 iOS 自帶的一個小例子(原文參見 Core Data Tutorial for iOS)。由於上次已講述基本概念和實現方法,這次描述會簡練一些。本次目標是創建一個應用程序,記錄每次保存的經緯度坐標,並可對這些坐標(保存為一個 Event 實體)進行編輯。演示環境為 Xcode 4.6.3。
完成後,工程中多了幾個文件:AppDelegate(.h 和 .m)、一個 .xib 界面描述文件、一個 Core Data 模型文件 .xcdatamodeld,以及引用的 CoreLocation.framework。AppDelegate.h 會自動生成相關 Core Data 處理:
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
顧名思義,applicationDocumentsDirectory 返回 app 的文檔路徑,數據將保存在那裡。
這裡的 stack 指 Core Data framework 中一系列對象的集合,它們協同工作,把模型從文件中取出或寫入文件。從類比角度說,Core Data 可被看作一個數據庫,保存記錄和表(其數據可能真的存在數據庫中,如 SQLite,但不一定)。最簡單和最頻繁使用的 Core Data Stack 結構如下:
其中你最常用的是 Managed Object Context 及其包含的 Managed Object 對象。
Managed Object 是一個 NSManagedObject 或其子類的對象,代表 Store 中保存的一條記錄,是一個由 Core Data 管理的模型。它始終與一個 Managed Object Context 相關聯。
Managed Object Context 是 NSManagedObjectContext 類的實例,代表應用中與數據有關的內存區域,主要職責是管理 managed object。它是應用的控制中樞,負責生命周期管理、驗證、關系維護、重做與取消等。新建或取回 Managed Object 時都要放入 context,所有操作都在內存中,直到通過 commit 提交修改為止。
下圖演示了記錄與對象的關系,注意有個 Nigel 對象沒有保存,所以 Store 中的 salary 仍是 50000,另外有兩個對象未納入 context 管理:
Managed Object Model 是 NSManagedObjectModel 類的實例,描述了數據庫的 Schema。一個模型是若干實體描述(NSEntityDescription)的集合,每個實體描述根據實體名字描述其類名及屬性。每個 Managed Object 都有對應的實體描述。由於 Core Data 用模型來描述 managed object 與數據庫記錄間的映射關系,因此改變模型時要格外小心(需通過版本管理來處理變更)。
PSC 扮演的角色是告訴 Core Data 如何管理數據,大多數時候你完全不用關心它。它是 NSPersistentStoreCoordinator 類的實例,管理一系列 persistent object store。在 iOS 中一般只有一個 store,但複雜應用可能有多個,此時 PSC 會統一管理,取回數據時匯總所有結果。
本小節實現 Table View Controller 相關功能:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface LocationsListViewController : UITableViewController <CLLocationManagerDelegate>
@property (nonatomic, retain) NSMutableArray *eventsArray;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) UIBarButtonItem *addButton;
@end
位置獲取相關代碼:
- (CLLocationManager *)locationManager {
if (locationManager != nil) {
return locationManager;
}
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.delegate = self;
return locationManager;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
addButton.enabled = YES;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
addButton.enabled = NO;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"Locations";
self.navigationItem.leftBarButtonItem = self.editButtonItem;
addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self action:@selector(addEvent)];
addButton.enabled = NO;
self.navigationItem.rightBarButtonItem = addButton;
[[self locationManager] startUpdatingLocation];
}
此時 addEvent 尚未實現。接著到 AppDelegate 類,將 didFinishLaunchingWithOptions 修改為直接 return YES;。至此本階段完成,運行即可看到初始界面。
本小節目標是添加事件並顯示在 ListView 中:
- (void)addEvent {
// 獲取當前位置
CLLocation *location = [locationManager location];
if (!location) {
return;
}
// 創建並配置一個新的 Event 實體實例
Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
CLLocationCoordinate2D coordinate = [location coordinate];
[event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]];
[event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]];
[event setCreationDate:[NSDate date]];
// 保存新事件
NSError *error = nil;
if (![managedObjectContext save:&error]) {
NSLog(@"Save Event failed.");
return ;
}
// 更新事件數組和 Table View
[eventsArray insertObject:event atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
Table View 的顯示代碼中,需設置 Cell 的 Identifier 為 Cell(區分大小寫),並將 Style 設為 Right Detail,用 NSDateFormatter 和 NSNumberFormatter 分別格式化時間與經緯度。此外還需實現 getManagedObjectContext 方法,從 AppDelegate 獲取 context,並在 viewDidLoad 末尾初始化 eventsArray 與 managedObjectContext。
獲取數據步驟:創建請求 -> 設置排序條件(可選)-> 執行查詢 -> 把數據放入準備好的數組:
-(void)loadData
{
// 創建請求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// 設置排序描述
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
// 執行請求
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(@"error loading data");
}
[self setEventsArray:mutableFetchResults];
}
刪除操作主要是覆蓋 commitEditingStyle 方法,刪除 Object 並更新界面顯示:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 刪除給定 index path 的 managed object
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:eventToDelete];
// 更新數組和 Table View
[eventsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// 提交更改
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// 處理錯誤
}
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// 創建新的對象並插入
}
}
至此,這個例子完成,運行即可查看效果。