首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS SQLite UPDATE 真機失效:數據庫文件放在主 Bundle 導致無寫入權限

     編輯:程式設計綜合問答

現象

模擬器 UPDATE 正常,真機執行 sqlite3_step 返回 SQLITE_DONE 但數據未變,無報錯。

根因:沙箱機制

iOS App 沙箱目錄結構:

  • App.app/(主 Bundle,**只讀**,簽名校驗,不可寫)
  • Documents/、**Library/**(可讀寫,備份/不備份)
  • tmp/(可讀寫,隨時可能被系統清理)

代碼中 _databasePath 若指向 [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"],真機即在只讀區,**任何寫操作靜默失敗**(SQLite 返回 SQLITE_DONE 但實際未落盤)。

修正:拷貝到 Documents 目錄

- (NSString *)databasePath {
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *targetPath = [docPath stringByAppendingPathComponent:@"my.db"];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:targetPath]) {
        NSString *srcPath = [[NSBundle mainBundle] pathForResource:@"my" ofType:@"db"];
        [fm copyItemAtPath:srcPath toPath:targetPath error:nil];
    }
    return targetPath;
}

後續打開:sqlite3_open([self.databasePath UTF8String], &db)

驗證技巧

  1. 真機運行後,Xcode → Window → Devices → Download Container → 查看 Documents/my.db 大小/修改時間
  2. 用 sqlite3 命令行打開該文件檢查數據是否更新
  3. 在 sqlite3_open 後檢查 sqlite3_errmsg(db) 是否為 "not an error"

延伸:只讀數據庫怎麼辦?

若數據庫純只讀(如字典、配置),可直接留在 Bundle 讀取,**但必須以只讀模式打開**:

sqlite3_open_v2([path UTF8String], &db, SQLITE_OPEN_READONLY, NULL);

避免誤觸發寫入導致崩潰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved