我有一個使用Sqlite數據庫來存儲一些數據和一些用戶配置的iPhone應用程序。我遇到的問題是,當我提交應用程序更新時,用戶安裝中的現有數據庫被空數據庫覆蓋,用戶失去了配置。我相信避免這種情況不會太難,但我不知道該怎麼做。如何保持應用程序更新的現有數據庫?
這是我創造的數據庫副本的方法的代碼:
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *writableDBPath = [self databasePath];
success = [fileManager fileExistsAtPath:writableDBPath];
if (!success) {
// The writable database does not exist, so copy the default to the appropriate location.
//NSLog(dbName);
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
}
這種方法被稱爲形式:
- (BOOL)openDatabase {
BOOL success = true;
if (!database) {
[self createEditableCopyOfDatabaseIfNeeded];
if (sqlite3_open([[self databasePath] UTF8String], &database) != SQLITE_OK) {
success = false;
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
}
return success;
}
- (NSString*)databasePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:dbName];
return path;
}
也許我忘了在我的代碼的東西嗎?
有人能幫我解決這個問題嗎?謝謝!
約瑟夫,謝謝你的回答,我認爲你是對的,那就是我需要的,但是我不能讓它工作。我添加了用於創建數據庫副本的代碼。謝謝。 – Sebastian 2010-11-11 18:24:07
究竟發生了什麼?請注意,BOOL應該是YES或NO,在Objective-C中不是真或假。 – 2010-11-11 19:33:29
強調應該,我認識的大多數人都是這樣使用它。所以如果我通過代碼,我會尋找是的,而不是真的... – 2010-11-11 19:41:34