在 iOS 中使用 SQLite3 儲存資料時,若需要保存陣列物件,不能直接把 NSArray 寫入一般文字欄位,而要先轉換成 NSData,再以 BLOB 型態存入資料庫。
建立表時,將欄位型別設為 blob:
NSString *createTableSQL = @"create table In_Editor(picUrls blob not null)";
使用 NSKeyedArchiver 將陣列序列化:
NSData *dataImageUrls = [NSKeyedArchiver archivedDataWithRootObject:model.imageUrls];
使用 executeUpdate 並以佔位符傳入 NSData:
[_db executeUpdate:@"insert into In_Editor (picUrls) values (?);", dataImageUrls];
從資料庫讀取 BLOB 後,使用 NSKeyedUnarchiver 還原:
NSArray *imageArr = [NSKeyedUnarchiver unarchiveObjectWithData:picUrls];
若未正確轉換型態,可能會出現類似以下錯誤:
NSInvalidArgumentException
-[__NSCFData objectForKey:]: unrecognized selector sent to instance
這通常代表程式把 NSData 當成 NSDictionary 使用。只要確認欄位為 BLOB、寫入前序列化、讀取後反序列化,即可避免此問題。