我们有一些代码来确定当前是否没有数据库文件。如果是这种情况,我们将基于文件系统上可能存在的某些文件执行一些初始化例程,以填充用户数据库(基本上是迁移例程)。
例程基本上是这样的
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
文件丢失/损坏,我们将无法找到检测这种情况的方法。在这种情况下,我们想进行数据完整性检查。
最佳答案
没有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();
}
}
}
关于ios - CoreData在启动时检测数据库不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36804690/