2013-10-24 13 views
-1

我正在更新數據庫中的條目,該語句工作並且代碼在數據庫中更新。一旦應用程序已關閉並重新打開,但數據庫尚未保存。它似乎創建一個臨時數據庫,然後不實際保存到應用程序正在讀取的數據庫。SQLite數據庫沒有保存在iOS上

這裏是我的代碼:

-(void)updateDatabase:(int)Level andPlayer:(int)questionID{ 
    DataClass *obj=[DataClass getInstance]; 
    //NSFileManager *filemgr = [NSFileManager defaultManager]; 
    NSString* Database =[NSString stringWithFormat:@"levelProgress.db"]; 
    NSString* databaseP = [[[NSBundle   mainBundle]resourcePath]stringByAppendingPathComponent:Database]; 
databasePath = [[NSString alloc]initWithString:databaseP]; 

const char *dbpath = [databasePath UTF8String]; 
sqlite3_stmt *statement; 

if (sqlite3_open(dbpath, &questionDB) == SQLITE_OK) { 
    NSString *querySQL = [NSString stringWithFormat:@"UPDATE levelProgress SET completed_questions=completed_questions+1 WHERE level=%d", obj.levelSelected]; 
    const char *query_stmt = [querySQL UTF8String]; 
    sqlite3_prepare_v2(questionDB, query_stmt, -1, &statement, NULL); 
    if(sqlite3_step(statement)==SQLITE_DONE){ 
     NSLog(@"update worked"); 
    }else{ 
     NSLog(@"did not work"); 
    } 
    sqlite3_finalize(statement); 
    sqlite3_close(questionDB); 
    } 
} 

任何幫助,將不勝感激。

+0

您無法更新只讀文件。 – rmaddy

回答

1

將數據庫文件databaseP從應用程序包複製到用戶文件夾中,然後進行更新。您無法更新應用程序包中的任何文件(它們始終只能讀取)。

#define kDatabaseName (@"levelProgress.db") 
- (void)checkAndCopyDatabaseIfNeeded 
{ 
    if (!self.databasePath) 
    { 
     // Database should be present in user sandbox at root. 
     self.databasePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], kDatabaseName, nil]]; 
    } 

    // Check if the file already copied/exists. 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    BOOL success = [fileManager fileExistsAtPath:self.databasePath]; 

    if(!success) 
    { 
     // Copy the file from app bundle to user sandbox (Files in app bundle can not be edited). 

     NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kDatabaseName]; 

#if DEBUG 
     BOOL isCopied = 
#endif 
     [fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil]; 

     NSAssert(isCopied, @"Problem copying database file to user document folder"); 
    } 
} 
+0

非常感謝這個,一旦文件在用戶文檔目錄中,用戶能看到我放入的文件嗎?如果可以,你能阻止他們看到文件的內容嗎? –

+0

該文件複製到應用程序沙箱的Documents目錄中,並且相當安全。在非越獄手機上,除您的應用外,其他人都無法訪問此文件。閱讀官方文檔(特別是 - 「應用程序沙盒」一節) - https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/TheiOSEnvironment/TheiOSEnvironment.html – Ashok

+0

如果數據庫不在圖書館/應用支持。將它放在文檔目錄中將允許用戶訪問該文件。我的Sqlite Db是一個可寫文件,但對用戶沒有任何意義。 – vijayst