将单独的.sqlite文件添加到ios项目

Dil*_*umN 3 sqlite iphone ios

我从SQLite Manager firefox插件创建了一个myDB.sqlite数据库.我想将myDB.sqlite文件添加到我的项目中.然后我可以编写函数来从表中获取数据.

我尝试将myDB.sqlite文件添加到项目文件夹并创建这样的文件路径.但我认为这个文件路径是错误的.

-(NSString *) filePath{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"document.sqlite"];
    return path;
}
Run Code Online (Sandbox Code Playgroud)

将myDB.sqlite文件添加到项目文件夹中是否正确?或者我应该在哪里保存这个myDB.sqlite文件以及我应该使用的文件路径是什么?

was*_*sim 6

在项目中添加myDB.sqlite文件.通过右键单击您的项目名称=>将文件添加到""projectName",然后添加它.

要获取文件路径,您可以在appDelegate中添加它

- (void) copyDatabaseIfNeeded {

//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(!success) {

   NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.sqlite"];
   success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

   if (!success)
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}

- (NSString *) getDBPath
{   
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(@"dbpath : %@",documentsDir);
return [documentsDir stringByAppendingPathComponent:@"myDB.sqlite"];
}
Run Code Online (Sandbox Code Playgroud)

在你完成启动方法调用[self copyDatabaseIfNeeded];