在iOS上覆盖SQLite数据库

时间:2017-06-03 19:58:54

标签: ios objective-c sqlite

我有一个database.sqlite文件,我用NSlog知道文件的位置,希望我得到了位置

问题是,我想用一个按钮覆盖该数据库,所以当用户单击该按钮时,它会覆盖数据库,但不会覆盖,而是将数据库保存到以下路径

  

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Bundle/Application/F15404E8-AB5B-40D6-A4D5-ED42F8F7A682/Documents/Database.sqlite < / p>

这不是我想要的,我想将数据库保存到这里

  

/用户/名为myUsername /库/开发商/ CoreSimulator /设备/ 4453818A-0617-479B-B98C-3FC544A24D00 /数据/容器/数据/应用/ BD3E2250-DF45-480F-AB06-F8E97D3B0B37 /文件

我尝试了以下代码:

- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}

2 个答案:

答案 0 :(得分:0)

我想你会想要使用:

[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]

而不是

[[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]

请参阅Apple的文档:

https://developer.apple.com/reference/foundation/nsfilemanager/1407726-urlsfordirectory?language=objc

(编辑)的

像这样:

- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}

答案 1 :(得分:0)

每次运行应用程序时,都会创建一个新的UUID并将文件复制到此新目录以验证这是否会在application:didFinishLaunchingWithOptions:

中添加以下代码
NSLog(@"executablePath: %@", [[NSBundle mainBundle] executablePath]);

NSURL *urlDocument = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *pathDatabase = [[urlDocument path] stringByAppendingPathComponent:@"Database.sqlite"];

BOOL databaseExists = [[NSFileManager defaultManager] fileExistsAtPath:pathDatabase];
NSLog(@"databaseExists: %@", databaseExists ? @"YES" : @"NO");

顺便说一下,在将数据库内容(filePath)写入此位置的文件之前,应检查文件是否存在于dbFile