当我最初为我的应用程序创建一个带有预先插入数据集的SQLite数据库文件时,我必须将此文件放在我的Xcode项目中的某个位置,以便它转到我的iPhone应用程序.我想"ressources"是正确的选择.
在iPhone应用程序中部署SQLite数据库文件的基本"步骤"是什么?
手动创建数据库
将数据库文件添加到项目中(其中?)
我目前正在阅读整个SQLite文档,尽管与iPhone不太相关.
您需要首先将SQLite文件添加到Xcode项目中 - 最合适的位置是在resources文件夹中.
然后在您的应用程序委托代码文件中,在appDidFinishLaunching方法中,您需要首先检查是否已创建SQLite文件的可写副本 - 即:已在用户文档文件夹中创建了SQLite文件的副本iPhone的文件系统.如果是,则不执行任何操作(否则您将使用默认的Xcode SQLite副本覆盖它)
如果不是,那么你在那里复制SQLite文件 - 使其可写.
请参阅下面的代码示例来执行此操作:这是从Apple的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)") } } }
如果您只是要查询数据,您应该可以将其保留在主数据包中.
然而,这可能不是一个好习惯.如果您将来扩展您的应用程序以允许数据库编写,您必须重新计算所有内容...