在哪里将您的SQLite数据库文件在iPhone应用程序?
发布时间:2020-12-12 19:17:54 所属栏目:百科 来源:网络整理
导读:当我最初为我的应用程序创建一个带有预先插入的数据集的SQLite数据库文件时,我必须将这个文件放在我的Xcode项目中的某个位置,以便它进入我的iPhone应用程序。我想“资源”是正确的地方。 在iPhone应用程序中部署SQLite数据库文件的基本“步骤”是什么? 手
当我最初为我的应用程序创建一个带有预先插入的数据集的SQLite数据库文件时,我必须将这个文件放在我的Xcode项目中的某个位置,以便它进入我的iPhone应用程序。我想“资源”是正确的地方。
在iPhone应用程序中部署SQLite数据库文件的基本“步骤”是什么? >手动创建数据库 我目前正在阅读整个SQLite文档,虽然这不是很多iPhone相关。 您需要首先将SQLite文件添加到您的Xcode项目 – 最适当的地方是在资源文件夹中。然后在您的应用程序委托代码文件中,在appDidFinishLaunching方法中,您需要首先检查是否已经创建了SQLite文件的可写副本 – 例如:已在用户文档文件夹中创建了SQLite文件的副本iPhone的文件系统。如果是,你不做任何事情(否则你会用默认的Xcode SQLite复制它) 如果没有,那么你复制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)") } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |