过去,我发布了带有预加载数据库的应用程序,因此用户无需在第一次运行时更新它。我在另一个问题中找到了一些代码(抱歉,不再有链接),我将其添加到我的应用程序代理中persistentStoreCoordinator
method:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"db.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]])
{
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"]];
NSError* err = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err])
{
NSLog (@"Error - Could not preload database.");
}
}
//... more code generated from the template here
}
当我尝试在 iOS 7 中执行此操作时,我没有收到任何错误,但数据库是空的(即使我的数据库中的数据库是空的)mainBundle
有我期待的所有信息)。我注意到有更多的数据库文件(一个 .sqlite-shm 文件和一个 .sqlite-wal 文件)applicationDocumentsDirectory
。我是否还需要对这些文件执行某些操作?或者应用程序不再可能附带预加载的数据库?
编辑:我尝试添加代码来复制新的 .sqlite-shm 和 .sqlite-wal 文件,但这没有帮助。
我也复制了 .sqlite-shm 和 .sqlite-wal 文件并且它有效:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *storePath = [documentsDirectory stringByAppendingPathComponent: @"emm_samples.sqlite"];
// Check if the sqlite store exists
if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) {
NSLog(@"File not found... copy from bundle");
// copy the sqlite files to the store location.
NSString *bundleStore = [[NSBundle mainBundle] pathForResource:@"emm_samples" ofType:@"sqlite"];
[[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:nil];
bundleStore = [[NSBundle mainBundle] pathForResource:@"emm_samples" ofType:@"sqlite-wal"];
storePath = [documentsDirectory stringByAppendingPathComponent: @"emm_samples.sqlite-wal"];
[[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:nil];
bundleStore = [[NSBundle mainBundle] pathForResource:@"emm_samples" ofType:@"sqlite-shm"];
storePath = [documentsDirectory stringByAppendingPathComponent: @"emm_samples.sqlite-shm"];
[[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:nil];
}
else {
NSLog(@"File exists");
}
(基于:App Bundle 中包含核心数据存储 https://stackoverflow.com/questions/5633079/core-data-store-included-in-app-bundle)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)