2016-04-22 23 views
1

我們有一些代碼來確定是否沒有當前創建的數據庫文件。如果是這種情況,我們會根據文件系統中可能存在的一些文件(基本上是遷移例程),執行一些初始化例程來填充用戶的數據庫。CoreData在啓動時檢測到數據庫不一致

的套路基本上是這樣的

NSURL * defaultStorePath = [NSPersistentStore MR_defaultLocalStoreUrl]; 
BOOL initializeDatabase = ![[NSFileManager defaultManager] fileExistsAtPath:[defaultStorePath path]];  

[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreAtURL:defaultStorePath]; 

if(initializeDatabase) 
    // ... ingest user files ... 

因此,如果.sqlite文件不存在,這個效果很好。但是,如果.sqlite-wal.sqlite-shm文件丟失/損壞,我們無法找到檢測此情形的方法。

我們想要做一個數據完整性檢查或在這種情況下的東西。

回答

1

沒有MagicalRecord

NSURL *storeURL = ... 
NSError *error; 
NSPersistentStore *persistentStore = [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]; 

if (persistentStore) { 
    // further initialization 
} else { 
    switch (error.code) { 
     case NSFileReadCorruptFileError: { 
      NSLog(@"database corrupted."); 
      // delete .sqlite, -wal and -shm 
      // make another attempt to add persistent store 
      break; 
     } 
     case NSPersistentStoreIncompatibleVersionHashError: { 
      NSLog(@"database model updated."); 
      // migrate 
      break; 
     } 
     default: { 
      NSLog(@"unresolved error %@", error.localizedDescription); 
      abort(); 
     } 
    } 
} 
+0

也許我們可以用MagicalRecord提交一個功能請求來幫助我們處理故障。謝謝 – yano

1

下面是一個例子,我希望這會有所幫助。

func configurePersistentStore() { 
    let nc = NSNotificationCenter.defaultCenter() 
    nc.addObserver(self, selector:#selector(self.dataBaseWillBeRecreated(_:)), name:kMagicalRecordPSCMismatchWillDeleteStore, object:nil) 

    MagicalRecord.setLoggingLevel(MagicalRecordLoggingLevel.Warn) 
    // if sqlite database does not match the model you provided, delete store. 
    // MagicalRecord.setShouldDeleteStoreOnModelMismatch(true) 
    MagicalRecord.setupCoreDataStackWithStoreNamed(kPersistentStoreName) 

    if ESGlobal.sharedInstance().firstRun { // User first run your app after installation. 
     self.fillDefaultDataToSQLiteDB() // fill data 
    } 
}