ios - 将 sqlite 数据库转换为 nsdata 并返回

标签 ios objective-c sqlite nsdata nsfilemanager

我将 sqlite 文件转换为 NSData 以将其保存在文档目录中。现在我将它转换为 sqlite 文件并将该文件保存在文档目录中,但是新的 sqlite 文件不是有效的 sqlite 文件,代码不会从中读取数据现在。下面是我用来将 NSData 转换为 sqlite 文件的代码:

-(void)openDataBase{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Demo.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];

if (success)
{
    NSData *data=[[NSData alloc]initWithContentsOfFile:writableDBPath];
    NSString * _key = @"111";
    NSData *decryptedData = [data AES256DecryptWithKey:_key];
  [fileManager createFileAtPath:writableDBPath contents:decryptedData attributes:nil];
    return;
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Demo.sqlite"];

NSData *SqliteData = [NSData dataWithContentsOfFile:defaultDBPath];

NSString * _key = @"111";

NSData *encryptedData = [SqliteData AES256EncryptWithKey:_key];

success= [fileManager createFileAtPath:writableDBPath contents:encryptedData attributes:nil];
if (!success)
{
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);} }


我的代码有什么问题,我想我一直在创建新的 sqlite 文件,但如何解决这个问题?
谁能帮助我如何将 NSData 转换为 sqlite 文件。 我应该在库中编写 sqlite 文件然后从那里访问它吗? 但是每次更新都会解密sqlite文件,我必须解密它。

最佳答案

如果文件已经存在,您的代码将解密并覆盖它。如果没有,您将默认数据库的加密副本写入磁盘。因此,默认情况下,您有一个无法使用的加密文件。

关于ios - 将 sqlite 数据库转换为 nsdata 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20016997/

相关文章:

ios - 图像高度限制不起作用

iphone - 通过触摸平滑旋转 UIView

ios - UIActivityViewController 共享应用列表为空

ios - 带侧面菜单的页面查看器(抽屉导航)

iphone - 为什么[object release]后retainCount还是1?

c# - 如何在跨平台应用程序之间共享 SQLite 代码?

ios - sqlite3_prepare_v2 () - 没有这样的表

javascript - SQLite 在 Javascript Node.JS 中将变量值插入为 Null

iOS UIAlertController 粗体按钮在 8.3 中更改

ios - 为什么我的 UITableViewCell 中的多行 UILabel 在第一次加载时被截断,但在滚动时会自行更正?