Prepopulate Core Data in iOS 5

后端 未结 1 733
星月不相逢
星月不相逢 2021-01-06 23:18

There seem to be some modifications to the NSPersistentStoreCoordinator method is iOS 5. I am trying to get a prepopulated database ... it doesn\'t seem to work

相关标签:
1条回答
  • 2021-01-07 00:05

    The problem is in the applicationDocumentsDirectory method that gives wrong absolute string. It is not really wrong, but is not suited for NSFileManager class.

    The solution is simple. You need to write another method which I called applicationDocumentsDirectory2.

    So first, go to header file of your AppDelegate and declare method:

    - (NSString *)applicationDocumentsDirectory2;
    

    Now, go to the .m file, and define a method:

    - (NSString *)applicationDocumentsDirectory2 {
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        return basePath;
    }
    

    And finally, just change persistentStoreCoordinator method into:

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    {
        if (__persistentStoreCoordinator != nil)
        {
            return __persistentStoreCoordinator;
        }
        NSError *error = nil;
    
       NSString *storePath = [[self applicationDocumentsDirectory2] stringByAppendingPathComponent: @"DataModel.sqlite"];
    
        /*
         Set up the store.
         For the sake of illustration, provide a pre-populated default store.
         */
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // If the expected store doesn't exist, copy the default store.
        if (![fileManager fileExistsAtPath:storePath]) {
            NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"DataModel" ofType:@"sqlite"];
            if (defaultStorePath) {
                if(![fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error]) {
                    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    
    
                }
            } 
        }
    
    
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"DataModel.sqlite"];
    
        __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
        {
    
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }    
    
        return __persistentStoreCoordinator;
    
    }
    

    That's it! :)

    0 讨论(0)
提交回复
热议问题