将文件添加到文档目录(或其他地方)?

发布于 2024-08-19 08:43:22 字数 126 浏览 3 评论 0原文

我想用一个小的 sqlite3 DB 初始化我的应用程序。我尝试将它放在 Documents 目录中,但有时它会以零大小复制它,有时它根本不复制它。

我应该如何使用充满信息的数据库初始化我的应用程序?

谢谢

I want to initialize my app with a small sqlite3 DB. I tried to put it in the Documents directory, but sometimes it copies it with zero size and sometimes it doesnot copy it at at all.

How sholud I initialize my app with a DB full of info?

Thankyou

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2024-08-26 08:43:22

如何将其复制到您的申请中?
如果您将应用程序与应用程序包内的数据库(作为资源)一起发送,则应将其从资源中复制到文档文件夹(如果不存在)并在那里使用它:

NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];
BOOL exists = [fileManager fileExistsAtPath:databasePath];

if (exists) {
    return;
}

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

How do you copy it with your application?
If you ship your application with DB inside app bundle (as a resource) you should copy it to the documents folder from resources if it is absent and work with it there:

NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];
BOOL exists = [fileManager fileExistsAtPath:databasePath];

if (exists) {
    return;
}

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
贱人配狗天长地久 2024-08-26 08:43:22

谢谢弗拉基米尔,

这很有帮助。我做了一些更改,这是效果很好的最终结果:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *databasePath = @"personalLMS.s3db";

NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];

NSString * databasePathFromApp = [[NSBundle mainBundle] pathForResource:@"personalLMS"  ofType:@"s3db"];

[fileManager copyItemAtPath:databasePathFromApp toPath:[documentsDirectory stringByAppendingPathComponent:databasePath] error:nil];

Thank you Vladimir,

This was helpful. I made a few changes and here is the final result that works great:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *databasePath = @"personalLMS.s3db";

NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];

NSString * databasePathFromApp = [[NSBundle mainBundle] pathForResource:@"personalLMS"  ofType:@"s3db"];

[fileManager copyItemAtPath:databasePathFromApp toPath:[documentsDirectory stringByAppendingPathComponent:databasePath] error:nil];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文