当我使用iPhone运行项目时,如何在iOS中使用sqlite

时间:2015-11-03 08:29:00

标签: ios sqlite

当我使用模拟器时,我可以在/ documents中找到数据库文件。但是当我使用我的iPhone运行项目时,我找不到数据库文件。 我应该在什么时候创建数据库文件或在我的项目中使用此代码?

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex:0];
NSString *dbFilePath = [documentFolderPath stringByAppendingString:DATABASENAME];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isExist = [fm fileExistsAtPath:dbFilePath];
if (!isExist) {
    NSString *backupDbPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:DATABASENAME];
    [fm copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];
}

2 个答案:

答案 0 :(得分:0)

第一次或文档目录中不存在数据库文件时,您必须将DB文件复制到文档目录:

-(void)copyDatabaseIntoDocumentsDirectory{
    // Check if the database file exists in the documents directory.
    NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
    if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
        // The database file does not exist in the documents directory, so copy it from the main bundle now.
        NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
        NSError *error;
        [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];

        // Check if any error occurred during copying and display it.
        if (error != nil) {
            NSLog(@"%@", [error localizedDescription]);
        }
    }
} 

参考:http://www.appcoda.com/sqlite-database-ios-app-tutorial/

答案 1 :(得分:0)

您无法访问iPhone或iPad的目录。因此,即使您成功创建了数据库,也无法看到它。您可以通过从中读取数据来判断其存在。