Search code examples
iphoneiossqlitecore-dataios6

iOS check if databse is already created and choose between to .sqlite files to load


I'm developing an iOS application that uses coredata. I have 2 .sqlite databases that should be loaded on the start of the application. One database has english information and the other has Portuguese information. I want my application to show only the first time that the application runs the selection of the language, and then the corresponding database should be loaded. After that I want another view to be loaded and the language selection should not appear again.

So far, I have my application that loads only one database at the start of the app. Can someone give me tips on how to do it? Sorry for the question not to be very specific :s

Thanks Best Regards


Solution

  • Basically, you need to allow the user to choose his language and then set up a new NSPersistentStore with a specific .sqlite file as seed data.

    You would do something like this (pardon the pseudocode)

    if (/*user chose English*/) {
    
      __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
      [self addSeedDataNamed: @"English.sqlite" toCoordinator:__persistentStoreCoordinator];
    
    }else if (/*user chose portuguese*/){
      [self addSeedDataNamed: @"Portuguese.sqlite" toCoordinator:__persistentStoreCoordinator];
    }
    
    - (void) addSeedDataNamed:(NSString *)name toCoordinator:(NSPersistentStoreCoordinator *)storeCoordinator
    {
      NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:name];
    
      NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSReadOnlyPersistentStoreOption, nil];
      [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
    }
    

    Answer mostly taken from here: http://blog.atwam.com/blog/2012/05/11/multiple-persistent-stores-and-seed-data-with-core-data/