iOS 7预填充核心数据数据库不包含所有数据

时间:2014-04-17 09:05:05

标签: ios objective-c core-data

我正在开发一个iOS应用程序,我希望附带预先填充的Core Data数据库。我在模拟器中填充了数据库一次,禁用了这段代码,每次我在模拟器中运行应用程序时,我都会在第一个视图控制器中执行检查,以查看我的数据库中有多少实体:

- (void) printNumberOfWords{

FWHAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context =[appDelegate managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *managedObjectContext = context;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Word" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

NSError *error = nil;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&error];

 if (!error){
    NSLog(@"in total %d words",count);
 }
 else
    NSLog(@"error with counting words");
 }
}

这总是打印出“总共1083个单词”,这是正确的 - 我希望有1083个单词。

所以我的下一步是将此文件添加到我的Xcode项目中,以便我可以将其与我的应用程序捆绑在一起。我将文件放在我的/ Users / myusername / Library / Application Support / iPhone Simulator / 7.1 / Applications / appname / Documents文件夹中,将其复制到我的Xcode项目中(选中“如果需要复制资源”和“添加到目标”字段) ),然后我修改了我的AppDelegate.m(复制形式由Apple提供的CoreDataBooks示例):

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{

if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Fit_Wit_Hit.CDBStore"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[storeURL path]]) {
    NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"Fit_Wit_Hit" withExtension:@"CDBStore"];
    if (defaultStoreURL) {
        [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
    }
}

NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES, NSInferMappingModelAutomaticallyOption: @YES};
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

NSError *error;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;
}

我从我的模拟器中删除了应用程序,再次运行它(并且导入的数据代码仍然被禁用,因此我知道数据库不会被我自己的代码填充),当我到达我检查的位置时有多少实体,它打印出“总共978个单词” - 所以105个实体比我预期的要少!

有谁知道为什么会这样?我想念我的一些数据,我真的不知道我在这里做错了什么。

更新 不得不禁用WAL模式,答案就在这里:How to disable WAL journal mode

1 个答案:

答案 0 :(得分:1)

由于iOS 7和Mac OS X 10.9的更改,SQLite商店包含包含更改的特殊文件。功能WAL journal_mode会生成一个wal文件,另外还有一个shm文件。

如果只复制单个数据库文件而不复制其他两个,则在某些情况下会看到缺少的条目。这是预期的行为。例如,请参阅:stackoverflow.com/questions/20062197 / ...,了解如何禁用WAL模式。