当我最初为我的应用程序创建一个带有预先插入的数据集的sqlite数据库文件时,我必须将这个文件放在我的Xcode项目中的某个位置,以便它进入我的iPhone应用程序。我想“资源”是正确的地方。
在iPhone应用程序中部署sqlite数据库文件的基本“步骤”是什么?
我目前正在阅读整个sqlite文档,虽然这不是很多iPhone相关。
您需要首先将sqlite文件添加到您的Xcode项目 – 最适当的地方是在资源文件夹中。
原文链接:https://www.f2er.com/sqlite/198135.html然后在您的应用程序委托代码文件中,在appDidFinishLaunching方法中,您需要首先检查是否已经创建了sqlite文件的可写副本 – 例如:已在用户文档文件夹中创建了sqlite文件的副本iPhone的文件系统。如果是,你不做任何事情(否则你会用默认的Xcode sqlite复制它)
看下面的代码示例来做:这是从苹果的sqlite书代码示例,其中此方法从应用程序委派appDidFinishLaunching方法调用。
// Creates a writable copy of the bundled default database in the application Documents directory. - (void)createEditableCopyOfDatabaseIfNeeded { // 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:@"bookdb.sql"]; 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:@"bookdb.sql"]; success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if (!success) { NSAssert1(0,@"Failed to create writable database file with message '%@'.",[error localizedDescription]); } }
============
这里是上面的代码在Swift 2.0
// Creates a writable copy of the bundled default database in the application Documents directory. private func createEditableCopyOfDatabaseIfNeeded() -> Void { // First,test for existence. let fileManager: NSFileManager = NSFileManager.defaultManager(); let paths:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true) let documentsDirectory:NSString = paths.objectAtIndex(0) as! NSString; let writableDBPath:String = documentsDirectory.stringByAppendingPathComponent("bookdb.sql"); if (fileManager.fileExistsAtPath(writableDBPath) == true) { return } else // The writable database does not exist,so copy the default to the appropriate location. { let defaultDBPath = NSBundle.mainBundle().pathForResource("bookdb",ofType: "sql")! do { try fileManager.copyItemAtPath(defaultDBPath,toPath: writableDBPath) } catch let unknownError { print("Failed to create writable database file with unknown error: \(unknownError)") } } }