【问题标题】:What is the best way to write a previously created Sqlite database to documents in iOS将以前创建的 Sqlite 数据库写入 iOS 文档的最佳方法是什么
【发布时间】:2011-12-14 13:38:46
【问题描述】:

我有一个之前创建的 Sqlite 数据库文件,我将它与 iOS 应用程序捆绑在一起。我的问题是将这些数据写入手机的最佳方式是什么,以便我可以从那里的应用程序中更改表格?

我的研究表明,我可能需要遍历整个 .sql 文件并在手机上手动插入/创建必要的表和值。

有没有办法只将数据库写入内部存储然后从那时起对其进行操作?

【问题讨论】:

    标签: iphone objective-c ios ipad sqlite


    【解决方案1】:

    您可以将其添加到项目中的支持​​文件中,然后将该文件复制为模板数据库,如果它不存在,然后打开它。一旦你打开它,你就可以用它做你想做的事。

    这是我的一个示例项目中的一些示例代码。在我的示例中,它是一个联系人数据库。请注意如果它不存在,则 ensurePrepared 将如何从包中复制它。我复制到库路径,但您可以复制到文档路径。

    - (BOOL)ensureDatabaseOpen: (NSError **)error
    {
        // already created db connection
        if (_contactDb != nil)
        {
            return YES;
        }
    
        NSLog(@">> ContactManager::ensureDatabaseOpen");    
        if (![self ensureDatabasePrepared:error])
        {
            return NO;
        }
    
        const char *dbpath = [_dbPath UTF8String]; 
        if (sqlite3_open(dbpath, &_contactDb) != SQLITE_OK &&
            error != nil)
        {
            *error = [[[NSError alloc] initWithDomain:@"ContactsManager" code:1000 userInfo:nil] autorelease];
            return NO;
        }
    
        NSLog(@"opened");
    
        return YES;
    }
    
    - (BOOL)ensureDatabasePrepared: (NSError **)error
    {
        // already prepared
        if ((_dbPath != nil) &&
            ([[NSFileManager defaultManager] fileExistsAtPath:_dbPath]))
        {
            return YES;
        }
    
        // db in main bundle - cant edit.  copy to library if !exist
        NSString *dbTemplatePath = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"db"];
        NSLog(@"%@", dbTemplatePath);
    
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        _dbPath = [libraryPath stringByAppendingPathComponent:@"contacts.db"];
    
        NSLog(@"dbPath: %@", _dbPath);
    
        // copy db from template to library
        if (![[NSFileManager defaultManager] fileExistsAtPath:_dbPath])
        {
            NSLog(@"db not exists");
            NSError *error = nil;
            if (![[NSFileManager defaultManager] copyItemAtPath:dbTemplatePath toPath:_dbPath error:&error])
            {
                return NO;
            }
    
            NSLog(@"copied");
        }    
    
        return YES;    
    }
    

    【讨论】:

      【解决方案2】:

      将数据库存储在包中(在项目中)。在 App Delegate 中,将数据库复制到 Documents 目录(仅当数据库文件不存在于文档目录中时才执行此操作,否则您将始终覆盖您的文件)。在您的代码中始终引用文档目录中的副本。
      另请阅读this SO Question 了解有关如何进行复制的一些代码。

      瞧。

      【讨论】:

      • 我会警惕 appDelegate 复制模型数据存储。应用程序委托不应该知道模型如何存储数据...
      • 我提供了 appDelegate,因为这是 Apple 的核心数据模板设置它的地方。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多