问题
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