2016-04-22 32 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 
    } 
}