iOS - Copy sqlite to bundle for CoreData

我的梦境 提交于 2019-12-08 06:08:44

问题


Here's what I've done: Created the sqlite file with a populated version of the app. Copied that file into my app bundle, making sure that the target is set and that it is present in "Copy Bundle Resources"

I then try to populate Core Data like this:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{  

if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"TestModel.sqlite"];


if( ![[NSFileManager defaultManager]
      fileExistsAtPath:[storeURL path]] ) {
    // If there’s no Data Store present (which is the case when the app first launches), identify the sqlite file we added in the Bundle Resources, copy it into the Documents directory, and make it the Data Store.
    NSString *sqlitePath = [[NSBundle mainBundle]
                            pathForResource:@"TestModel" ofType:@"sqlite"
                            inDirectory:nil];
    NSError *anyError = nil;
    BOOL success = [[NSFileManager defaultManager]
                    copyItemAtPath:sqlitePath toPath:[storeURL path] error:&anyError];

    if(success){
        NSLog(@"sucess, loading into store");
        NSError *error = nil;
        _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();
        }else{
            NSLog(@"error with sqlite file");
        }
    }
}

return _persistentStoreCoordinator;

}

But I get this error:

NSFileManager copyItemAtPath:toPath:error:]: source path is nil

What am I doing wrong? Is it saying that it can't find the sqlite file in the bundle?


回答1:


I think this happened because when I imported the file from Finder into Xcode, it was named "TestModel" instead of "TestModel.sqlite".




回答2:


From documentation

bundlePath -- The path of a top-level bundle directory. This must be a valid path. For example, to specify the bundle directory for a Mac app, you might specify the path /Applications/MyApp.app.

*edit: I think I got the wrong method :(, still try this one though!-> Why not use - (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension? Skip the directory (Since you didn't want one anyway).



来源:https://stackoverflow.com/questions/12309828/ios-copy-sqlite-to-bundle-for-coredata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!