資料儲存幾乎是每個 App 都會碰到的課題。iOS 提供了多種儲存機制,各有適用場景。本文整理常見的幾種方式,並附上關鍵程式碼,幫助你依需求做出正確選擇。
iOS 常見的資料儲存機制包括:
屬性列表適合用來儲存簡單的資料結構(如陣列、字典)。寫入時先取得 Documents 目錄路徑,再把資料寫入 plist 檔:
// 取得資料檔案的完整路徑
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
// App 即將失去焦點時,將資料存入屬性列表
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: field1.text];
[array writeToFile:[self dataFilePath] atomically:YES];
}
// 讀取時
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
當需要儲存自訂物件時,可讓該類別實作 NSCoding 協定,透過 encodeWithCoder 與 initWithCoder 進行編碼與解碼:
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:field1 forKey:kField1Key];
// 其餘欄位同理
}
-(id) initWithCoder:(NSCoder *)aDecoder {
if(self = [super init]) {
field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
}
return self;
}
儲存時使用 NSKeyedArchiver 編碼後寫檔,讀取時則用 NSKeyedUnarchiver 解碼還原物件。
SQLite 是輕量級的關聯式資料庫,適合用來儲存大量、需要查詢的結構化資料。寫入時使用 prepared statement 預編譯 SQL:
char *update = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES (?, ?);";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, i);
sqlite3_bind_text(stmt, 2, [field.text UTF8String], -1, NULL);
}
sqlite3_step(stmt);
sqlite3_finalize(stmt);
注意:bind 參數的 index 從 1 開始,而取出資料時欄位的 index 從 0 開始。查詢時則用 sqlite3_prepare_v2 搭配 sqlite3_step 逐列讀取。
Core Data 是蘋果提供的物件圖管理框架,透過 NSManagedObjectContext 操作資料。儲存時建立 NSFetchRequest 與 NSEntityDescription,寫入物件後呼叫 save 通知上下文保存:
NSManagedObject *theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line" inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
[theLine setValue:theField.text forKey:@"lineText"];
[context save:&error];
讀取時同樣建立 fetch request,再透過 executeFetchRequest 取得結果並逐一讀出欄位。
適合儲存少量的設定值(如偏好設定、開關狀態),寫法最為簡潔:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
這種方式即自行透過 IO 將資料寫入檔案,或從檔案讀取。適合儲存不受結構限制的任意內容。
簡單的設定值用 NSUserDefaults 即可;小型結構化資料可用屬性列表;自訂物件可用物件歸檔;大量且需查詢的資料適合 SQLite 或 Core Data。依資料的性質與規模選擇合適的方案,才能兼顧效能與開發效率。