2010-01-11 81 views
2

我將已填充的現有sqlite3文件複製到我的項目中;它被發現(我檢查與iPhone Core Data無法從Sqlite3中獲取任何數據

- (void)createEditableCopyOfDatabaseIfNeeded { 
    NSLog(@"Checking if we have to create editable copy of database"); 

    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"hvw.sqlite"]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) return; 
    NSLog(@"Creating editable copy of database"); 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"hvw.sqlite"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
     NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

我不來-part「數據庫的創建可編輯的副本」,因此該文件是存在的,發現的。

但我取不返回任何結果:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Game" inManagedObjectContext:managedObjectContext]; 

[request setEntity:entity]; 

NSError *error; 

NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; 

不引發錯誤,但結果數組是空的...

編輯

我取代了線

NSString *documentsDirectory = [paths objectAtIndex:0]; 

通過

NSString *documentsDirectory = [self applicationDocumentsDirectory]; 

,並在日誌文件中我看到錯誤,當設法保存或閱讀對象:

Operation could not be completed. (Cocoa error 256.) 

回答

1

了這SQLite數據庫使用核心數據創建?你不能只使用你想要的永久存儲的SQLite數據庫,它必須具有Core Data使用的確切的內部格式。

如果這是您想要引入Core Data的標準SQLite數據庫,我的建議是編寫一個遷移方法,該方法接受SQLite並從中創建Core Data託管對象,設置所有適當的關係。遷移操作完成後,您可以將生成的永久存儲區寫出到磁盤,然後將其用於應用程序中的核心數據。如果您更冒險,可以在後臺線程上進行此遷移,並在從SQLite中分析通知時將託管對象添加到主線程的託管對象上下文中。

+0

我認爲我的sqlite文件具有它所需要的結構... 我根據http://ablogontech.wordpress.com/2009/07/13/using-a-pre-populated-sqlite -database-with-core-data-on-iphone-os-3-0/ – swalkner 2010-01-11 18:05:55

+0

如果我理解這篇文章是正確的,他從Core Data創建了一個空白的SQLite數據庫,然後用手工填充它中的數據?這並不能保證您的元素的關係和其他數據將採用Core Data期望的格式。 – 2010-01-11 19:11:26

+0

嗯......但我如何使用預先填充的數據庫呢? – swalkner 2010-01-11 19:14:42