[英]How to copy database file in Application Support directory in Cocoa without losing data?
我尝试过这段代码,但它在文档目录中创建了BLANK
database.sqlite
文件。
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"prediction.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"prediction.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
如何确保在复制数据库文件时不会创建空数据库?
任何帮助将不胜感激。
首先,您的代码不是尝试创建数据库文件。
那么......您只想将数据库文件“prediction.sqlite”从源包复制到UserDomain目录? 如果这是你的目的,你应该注意代码:
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
正确的应该是:
if (!success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSSearchPathForDirectoriesInDomains
返回的目录不保证存在; 如有必要,您需要自己创建它们(请参阅文档 )。 NSFileManager的createDirectoryAtPath:withIntermediateDirectories:attributes:error:
可以帮助解决这个问题。@ Anomie
尝试这些代码:(在复制“prediction.sqlite”文件之前,需要将文件添加到项目包中。):
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"prediction.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (!success){
// create the directories, because the directories returned by NSSearchPathForDirectoriesInDomains are not guaranteed to exist
if (![fileManager createFileAtPath:writableDBPath contents:nil attributes:nil]) {
return;
}
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"prediction.sqlite"];
// remove the same file, before you copy the file
[fileManager removeItemAtPath:writableDBPath error:nil];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.