当我最初为我的应用程序创建一个带有预插入数据集的SQLite数据库文件时,我必须将这个文件放在我的Xcode项目中的某个地方,这样它就可以进入我的iPhone应用程序了。我想“资源”是正确的地方。
在SQLite应用程序中部署iPhone数据库文件的基本“步骤”是什么?
创建数据库的manually
我目前正在阅读整个SQLite文档,尽管这与iPhone没有多大关系。
发布于 2009-04-04 13:48:35
您需要首先将SQLite文件添加到Xcode项目中--最合适的位置是在“资源”文件夹中。
然后,在应用程序委托代码文件中,在appDidFinishLaunching方法中,您需要首先检查是否已经创建了SQLite文件的可写副本--即:在iPhone文件系统的用户文档文件夹中创建了SQLite文件的副本。如果是,则什么也不做(否则会用默认的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)")
        }
    }
}发布于 2009-04-05 03:37:28
如果您只是要查询数据,您应该能够将其保留在主包中。
然而,这可能不是一个好做法。如果您将来要扩展您的应用程序以允许数据库的编写,那么您必须再次解决所有的问题.
https://stackoverflow.com/questions/717108
复制相似问题