在 iOS 應用開發裡,資料的持久化保存是每一個專案都繞不開的核心環節。無論是保存使用者偏好、快取網路資料,還是管理大量結構化記錄,選擇合適的儲存機制都能讓架構更清晰、效能更優越。本文以實作範例為主線,系統梳理 iOS 平台常見的六種資料儲存方式,並附上關鍵程式碼,方便你對照動手實作。
下面我們逐一拆解每種方式的原理與用法。
屬性列表是 iOS 中最直觀的一種儲存方式,適合用來保存陣列、字典這類基礎集合物件。核心思路是:先取得應用程式沙盒中 Documents 目錄的完整路徑,再把資料寫入以 .plist 結尾的檔案中。應用程式即將進入非啟用狀態時,是保存資料的理想時機。
// 取得資料檔案的完整路徑
- (NSString *)dataFilePath {
// 檢索 Documents 目錄,第二個參數表示把搜尋範圍限制在應用程式沙盒內
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// 每個應用程式只有一個 Documents 目錄
NSString *documentsDirectory = [paths objectAtIndex:0];
// 拼接檔名
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
// 應用程式即將失去活躍狀態時,把資料寫入屬性列表
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:field1.text];
[array addObject:field2.text];
[array addObject:field3.text];
[array addObject:field4.text];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
讀取時,先判斷檔案是否存在,若存在則透過 initWithContentsOfFile: 直接還原成陣列,再把值回填到各個輸入框即可。這種方式的優點是簡單易用,缺點是只能儲存基礎型別,不適合複雜物件。
當你需要儲存自訂的複合物件時,物件歸檔就派上用場了。要讓自訂類別支援歸檔,必須遵循 NSCoding 與 NSCopying 協議,並實作編碼與解碼方法。
#define kField1Key @"Field1"
#define kField2Key @"Field2"
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:field1 forKey:kField1Key];
[aCoder encodeObject:field2 forKey:kField2Key];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];
}
return self;
}
儲存時透過 NSKeyedArchiver 把物件編碼成二進位資料再寫檔;讀取時則用 NSKeyedUnarchiver 解碼還原。相比屬性列表,歸檔能保存任意自訂物件,靈活性大幅提升。
SQLite 是一套輕量級的關聯式資料庫,非常適合管理大量、需要條件查詢的結構化資料。iOS 直接內建了 sqlite3 函式庫,使用時需引入 <sqlite3.h> 標頭檔。
#import <sqlite3.h>
- (void)applicationWillResignActive:(NSNotification *)notification {
sqlite3 *database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, @"Failed to open database");
}
char *update = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES (?, ?);";
sqlite3_stmt *stmt;
// 將 SQL 語句編譯為 sqlite 內部結構,類似 JDBC 的 PreparedStatement 預編譯
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
// bind 參數的 index 從 1 開始,取資料時列的 index 從 0 開始
sqlite3_bind_int(stmt, 1, 1);
sqlite3_bind_text(stmt, 2, [field.text UTF8String], -1, NULL);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
sqlite3_close(database);
}
建立資料表時使用 CREATE TABLE IF NOT EXISTS,查詢時透過 sqlite3_prepare_v2 預編譯後,用迴圈搭配 sqlite3_step 逐列取出資料。用完記得呼叫 sqlite3_finalize 釋放 statement 佔用的記憶體,最後關閉資料庫。
Core Data 是蘋果官方提供的物件圖管理框架,本質上仍會落地到 SQLite,但開發者操作的是物件而非 SQL。使用前需從 AppDelegate 取得 NSManagedObjectContext,再透過實體描述與提取請求來完成增刪查改。
- (void)applicationWillResignActive:(NSNotification *)notification {
Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
// 建立提取請求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription =
[NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
[request setEntity:entityDescription];
// 設定檢索條件
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", 1];
[request setPredicate:pred];
// 建立新的托管物件來保存資料
NSManagedObject *theLine =
[NSEntityDescription insertNewObjectForEntityForName:@"Line" inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:1] forKey:@"lineNum"];
[theLine setValue:field1.text forKey:@"lineText"];
// 通知上下文保存變更
[context save:&error];
}
Core Data 的優勢在於資料模型清晰、支援物件關聯與懶載入,是大型應用管理複雜資料的首選。
如果你只需要保存少量、輕量的設定資料(例如開關狀態、上次登入帳號),NSUserDefaults 是最省事的选择:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:@"someValue" forKey:@"key"]; [defaults synchronize];
最後一種是最原始的方式——透過 IO 操作直接把資料寫入檔案,或從檔案讀取。這方式賦予開發者最大的掌控權,可自訂任意格式,但相對也需要自己處理序列化與錯誤判斷。
實務上,可以依資料特性來取捨:輕量設定用 NSUserDefaults;少量集合用屬性列表;自訂物件用歸檔;大量結構化資料用 SQLite 或 Core Data。掌握這六種方式,你就能應對絕大多數 iOS 資料持久化的場景。