2011-06-06 69 views
2

我有一款应用程序利用Core Data SQLITE3在模拟器中完美工作。不过,我不明白如何更新设备上的数据库,我想这与应用商店中的相同。在设备和应用商店刷新SQLITE3(核心数据)

我更新应用程序中的.txt文件中的数据库,并创建数据库,此功能仅用于创建数据库,并将在最终版本中删除。我的想法是在模拟器中创建数据库,锁定代码的更新部分,然后用更新的数据库分发包。

但是,当我在设备上重建我的应用程序时,它仍然具有数据库中的旧数据。

我一直在环顾四周,但我恐怕不完全明白如何解决这个问题。我确实发现这个线程:Can't refresh iphone sqlite3 database

我非常感谢,如果一些好人可以分享一些光线,并帮助我解决这个问题。

干杯

回答

0

有复制从包目录(只读)数据库文件,可写的? (如每个应用程序的文档目录?)。

当试图保存在设备中,你会得到像这样的sqlite错误?

SQLITE_READONLY  8 /* Attempt to write a readonly database */ 

编辑:

所有主束的文件是只读的,所以如果你需要修改一个/他们中的一些,你需要将文件是可写的一个位置复制。假设你已经调用了db mydb.sqlite,这里有一些将db复制到文档目录的代码(仅当它不存在时)。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    NSString *docPath = [docDirectory stringByAppendingPathComponent:@"mydb.sqlite"]; 
    if (![fm fileExistsAtPath:docPath]) { // file does not exists, copy it 
     NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"sqlite"]; 
     NSError *error = nil; 
     BOOL res = [fm copyItemAtPath:bundlePath toPath:docPath error:&error]; 
     if (!res) { 
      // do something with error 
     } 
    } 
+0

感谢您的回答朱利亚诺,不,我没有,我恐怕我真的不知道该怎么做? – PeterK 2011-06-06 09:39:33

0

实际上,在Bundle中使用.db文件 - 这是一个非常糟糕的主意。 每当我使用.db文件时,我正在检查,如果它已经存在于我的应用程序文档目录中,然后我将重写它。

#define DB_SHOULD_BE_REWRITTEN YES //You should update database and change allready existing db file to file from bundle 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"]; 


    BOOL success = [fileManager fileExistsAtPath:writableDBPath]; 

    if (!success || DB_SHOULD_BE_REWRITTEN) 
    { 
     // The writable database does not exist, so copy the default to the appropriate location. 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"]; 
     success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
     if (!success) { 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
     } 
    } 

    dbPath = writableDBPath; 
相关问题