Предварительно загруженная база данных базовых данных не работает - PullRequest
0 голосов
/ 19 февраля 2012

Я создал базовую базу данных в одном приложении, которое включало извлечение информации из API и заполнение базы данных.

Теперь я хотел бы использовать ее в другом приложении.

Iскопировал файл .xcdatamodeld и классы NSManagedObject.

Я добавил и импортировал инфраструктуру Core Data.

Я скопировал файл .sqlite в ресурсы моего нового приложения в качестве базы данных по умолчанию.

Я использую следующий код, который должен скопировать базу данных по умолчанию в каталог документов и открыть ее, чтобы я мог выполнять запросы к ней.

Это вызывает сбой приложения снет сообщения об ошибке, есть мысли о том, где я иду не так?

Если бы я должен был создать базу данных здесь с помощью saveToURL, я знаю, что имя файла будет постоянным, а не 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 Ответ

1 голос
/ 19 февраля 2012

У меня был другой взгляд, и я не уверен, что вы делаете, но этот код ниже, что я делаю, чтобы ответить на ваш вопрос.Я проверяю, существует ли работающая база данных, и, если она не существует, я перемещаю ее из пакета приложений, а затем продолжаю загружать ее.Я оставил комментарии к шаблону 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;
}
...