【发布时间】:2012-08-07 06:19:55
【问题描述】:
我已经阅读了 Apple 的数据存储指南,并且对于我应该将我在我的应用程序中创建的 sqlite 数据库文件保存在哪里感到非常困惑。即使应用程序处于离线模式,我也想从 sqlite 文件中读取。我读到创建的此类文件应保存在库/缓存中,并设置“不备份”标志。请建议我做同样事情的正确方法。
【问题讨论】:
标签: iphone ios5 xcode4.2 data-storage
我已经阅读了 Apple 的数据存储指南,并且对于我应该将我在我的应用程序中创建的 sqlite 数据库文件保存在哪里感到非常困惑。即使应用程序处于离线模式,我也想从 sqlite 文件中读取。我读到创建的此类文件应保存在库/缓存中,并设置“不备份”标志。请建议我做同样事情的正确方法。
【问题讨论】:
标签: iphone ios5 xcode4.2 data-storage
答案取决于您的数据库文件是如何创建的:
According to the Data Storage Guidelines page:
只有用户生成的或您的应用程序无法重新创建的文档和其他数据才能存储在 /Documents 目录,将自动 由 iCloud 备份。
可以再次下载或重新生成的数据应存储在 /Library/Caches 目录中。文件示例 你应该在 Caches 目录下包含数据库缓存文件 和可下载的内容,例如杂志、报纸使用的内容, 和地图应用程序。
这对我来说似乎比较清楚:如果您的应用程序以编程方式创建某些内容或生成您想要保存的数据,请将其放在“缓存”文件夹中。如果这是客户自己生成的独特内容(通过键盘输入或他们手动干预并执行的操作),请将其放入“文档”中。
“不备份”意味着文件永远不会发送到 iCloud,如果丢失,则必须从头开始重新创建(或重新安装)。
【讨论】:
这可能会对您有所帮助。将数据库复制到documents目录就足够了,bundle上的文件是只读的,在某些情况下如果您需要随时更新,更好的方法是首先复制数据库,如果它不存在于documents目录中。
复制数据库到documents目录的示例代码如下:
-(void) checkAndCreateDatabase {
// Setup some globals
NSString *databaseName = @"AnimalDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
你可以参考这个Tutorial 文件目录下的文件、内容是读、写模式,所以你可以从数据库中读取内容。
【讨论】: