预加载的核心数据数据库不起作用

时间:2012-02-18 22:42:06

标签: objective-c ios core-data

我在一个应用程序中创建了一个核心数据库,其中包括从API中提取信息并填充数据库。

我现在想在另一个应用程序中使用它。

我已经复制了.xcdatamodeld文件和NSManagedObject类。

我已经添加并导入了Core Data框架。

我已将.sqlite文件复制到我的新应用程序资源中作为默认数据库。

我正在使用以下代码,该代码应该将默认数据库复制到Documents目录并打开它,以便我可以对它执行查询。

它导致应用程序崩溃,没有错误消息,对我出错的地方有任何想法?

如果我在这里使用saveToURL创建数据库,我知道文件名将是persistentStore而不是Trailer.sqlite,如下所示,是否相关?

由于

- (void)viewDidLoad
{
[super viewDidLoad];


// Get URL -> "<Documents Directory>/<TrailerDB>" 
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

url = [url URLByAppendingPathComponent:@"TrailerDB"];

UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];

// Copy out default db to documents directory if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:[url path]]) {
    NSString *defaultDB = [[NSBundle mainBundle] 
                                  pathForResource:@"trailerdatabase" ofType:@"sqlite"];
    if (defaultDB) {

        [fileManager copyItemAtPath:defaultDB toPath:[url path] error:NULL];

    }
}

if (doc.documentState == UIDocumentStateClosed) {

    // exists on disk, but we need to open it
    [doc openWithCompletionHandler:^(BOOL success) 
     {

         if (success) [self useDatabase:doc];

         if (!success) NSLog(@"couldn’t open document at %@", url);


     }];

} else if (doc.documentState == UIDocumentStateNormal) 
{
    [self useDatabase:doc];
}

}

1 个答案:

答案 0 :(得分:1)

我又看了一眼,我不确定你在做什么,但下面的代码是我所做的,它会回答你的问题。我检查工作数据库是否存在,如果不存在,我将其从应用程序包中移动到位,然后继续加载它。我已经从Apple模板中留下了股票评论,因为我认为它们最终可能会有所帮助。

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"workingDataBase.sqlite"];

    NSError *error = nil;

    if (![[NSFileManager defaultManager] fileExistsAtPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent: @"workingDataBase.sqlite"]]){
        //database not detected
        NSLog(@"database not detected");
        NSURL  * defaultDatabase = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"DefaultData" ofType:@"sqlite"]];
        NSError * error;
        if (![[NSFileManager defaultManager] copyItemAtURL:defaultDatabase toURL:storeURL error:&error]){
            // Handle Error somehow!
            NSLog(@"copy file error, %@", [error description]);
        }
    }

    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

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

    return __persistentStoreCoordinator;
}