ios - CoreData在启动时检测数据库不一致

标签 ios sqlite core-data magicalrecord

我们有一些代码来确定当前是否没有数据库文件。如果是这种情况,我们将基于文件系统上可能存在的某些文件执行一些初始化例程,以填充用户数据库(基本上是迁移例程)。

例程基本上是这样的

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/

相关文章:

ios - ViewContext 没有收到来自 newBackgroundContext() 的更新

objective-c - NSSortDescriptor 问题

ios - 为什么 AVFoundation 合并后第二个视频播放为黑色?

c++ - 覆盖 AudioBufferList.mBuffers[0].mData?

ios - 在没有 Systemhint 的情况下检查蓝牙关闭

c#、System.Data.Sqlite 和 Ñ 字符

android - 更新数据库。 Sqlite-asset-helper 库

ios NSFetchRequest,订购子对象

ios - - (减)对边距等的约束值?

android.database.sqlite.SQLiteException : near "?": syntax error (code 1):