Core Data 的學習曲線多半卡在名詞上。先把幾個核心對象的角色理清,後面的代碼就都對得上號了。
NSEntityDescription 是「實體描述」,相當於資料庫裡的表結構定義,只描述結構,不存實際資料。真正的每一筆資料由 NSManagedObject 承載,實務上我們會建立它的子類來對應實體,讓屬性可以直接用點語法存取。
Xcode 提供了快速生成子類的功能:開啟 .xcdatamodeld 檔,點上方工具列的 Editor,選擇 Create NSManagedObject Subclass,在彈出的視窗中勾選要生成的實體即可。


生成後,Xcode 會自動建立對應檔案,裡頭已經宣告好各實體的屬性。
Core Data 的堆疊是固定的四層:模型 → 持久化協調者 → 上下文 → 資料對象。下面這段代碼把整個流程走了一遍:
// 讀取數據模型文件
NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
// 建立持久化存儲協調者
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
// 資料庫存放路徑
NSURL *path = [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
// 為協調者掛上一個存儲棧
/*
支持的存儲類型:
NSSQLiteStoreType // SQLite
NSXMLStoreType // XML
NSBinaryStoreType // 二進制
NSInMemoryStoreType // 記憶體
*/
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:path options:nil error:nil];
// 建立管理對象上下文
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
// 依實體名建立資料對象
SchoolClass *modelS = [NSEntityDescription insertNewObjectForEntityForName:@"SchoolClass" inManagedObjectContext:moc];
// 賦值
modelS.name = @"第一班";
modelS.stuNum = @60;
// 保存
if ([moc save:nil]) {
NSLog(@"新增成功");
}
NSLog(@"%@", [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:@"CoreDataExample.sqlite"]);
執行後到打印出的路徑下查看,會發現多了一個 sqlite 檔,裡頭的表中已經多了一筆資料。
Core Data 透過「請求對象」NSFetchRequest 來查詢,它主要負責兩件事:條件範圍的篩選,以及結果的排序與返回類型。
// 建立某個實體的查詢請求,等同於「在這張表裡查」
+ (instancetype)fetchRequestWithEntityName:(NSString*)entityName;
// 查詢條件
@property (nullable, nonatomic, strong) NSPredicate *predicate;
// 排序規則
@property (nullable, nonatomic, strong) NSArray<NSSortDescriptor *> *sortDescriptors;
// 最多返回幾筆
@property (nonatomic) NSUInteger fetchLimit;
// 返回類型
/*
typedef NS_OPTIONS(NSUInteger, NSFetchRequestResultType) {
NSManagedObjectResultType = 0x00, // 管理對象
NSManagedObjectIDResultType = 0x01, // 對象 ID
NSDictionaryResultType = 0x02, // 字典
NSCountResultType = 0x04 // 僅數量
};
*/
@property (nonatomic) NSFetchRequestResultType resultType;
// 是否包含子實體
@property (nonatomic) BOOL includesSubentities;
// 只取指定屬性
@property (nullable, nonatomic, copy) NSArray *propertiesToFetch;
查詢 SchoolClass 實體中 stuNum 等於 60 的資料:
// 建立查詢請求 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"]; // 設置條件 [request setPredicate:[NSPredicate predicateWithFormat:@"stuNum == 60"]]; // 執行查詢 NSArray *res = [moc executeFetchRequest:request error:nil]; NSLog(@"%@", [res.firstObject stuNum]);
如果資料要直接餵給 UITableView,更省事的做法是用 NSFetchedResultsController。它需要一個請求對象和一個上下文:
@interface ViewController () <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *_fecCon; // 數據橋接對象
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 建立 Core Data 堆疊
NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSURL *path = [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:path options:nil error:nil];
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
// 請求對象必須設置排序規則
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
[request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"stuNum" ascending:YES]]];
// 初始化橋接對象;第三個參數若設置,會以該鍵值做分區
_fecCon = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:moc
sectionNameKeyPath:nil
cacheName:nil];
_fecCon.delegate = self;
[_fecCon performFetch:nil];
}
@end
兩個容易忽略的細節:一是請求對象必須有排序規則,否則初始化會失敗;二是 sectionNameKeyPath 一旦設置,資料就會依該屬性分區,之後所有行操作都要跟著分區走。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellid"];
}
// 直接從橋接對象取值
SchoolClass *obj = [_fecCon objectAtIndexPath:indexPath];
cell.textLabel.text = obj.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"有%@人", obj.stuNum];
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [_fecCon sections].count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id<NSFetchedResultsSectionInfo> info = [_fecCon sections][section];
return [info numberOfObjects];
}

這是 NSFetchedResultsController 真正的價值所在:資料一改,界面可以精準地做增刪改的動畫,而不必整表刷新。
// 內容即將改變
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] beginUpdates];
}
// 分區層級的變化
- (void)controller:(NSFetchedResultsController *)controller
didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex
forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[[self tableView] insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
case NSFetchedResultsChangeUpdate:
break;
}
}
// 行層級的變化
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
switch(type) {
case NSFetchedResultsChangeInsert:
[[self tableView] insertRowsAtIndexPaths:@[newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[[self tableView] deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self reloadData];
break;
case NSFetchedResultsChangeMove:
[[self tableView] deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[[self tableView] insertRowsAtIndexPaths:@[newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
// 內容變更結束
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] endUpdates];
}
最後補一點實務經驗:所有對 context 的讀寫都必須在同一個隊列上進行。示例用的是 NSMainQueueConcurrencyType,與 UI 同隊列,簡單但要注意別在背景執行長耗時操作;若確實需要背景寫入,應改用私有隊列類型的 context,再把結果 merge 回主上下文。