2012-02-08 74 views
0

我无法确定为什么无法找到db.sqlite。我将它添加到项目的资源目录中。它在那里。 这里是我如何检查现有的一些代码。找不到数据库文件

-(void)getDatabaseLocation 
{ 
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *docsDir = [dirPaths objectAtIndex:0]; 

    // Build the path to the database file 
    NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"db.sqlite"]]; 

    NSFileManager *filemgr = [NSFileManager defaultManager]; 
    if ([filemgr fileExistsAtPath: databasePath ] == NO) 
    { 
     NSLog(@"NO"); // It's say no when this method is called. 
    } 
    else 
    { NSLog(@"YES"); 
    } 
} 

//编辑 现在我检查,在DOCSDIR的路径不存在。

回答

2

当然它不在那里。您必须首先将资源复制到文档目录,如下所示:

if (![filemgr fileExistsAtPath:databasePath]) 
{ 
    [filemgr copyItemAtPath:[NSBundle.mainBundle pathForResource:@"db" ofType:@"sqlite"] toPath:databasePath error:nil]; 
} 

编辑:如果你只需要对数据库做(没有编辑)上查找,那么你可以简单地这样做:

databasePath = [NSBundle.mainBundle pathForResource:@"db" ofType:@"sqlite"]; 
+0

他只需要将其复制到docdir,如果他想修改它。仅查找它可以简单地保留在资源目录中。 – 2012-02-08 15:05:31

+0

我只需要数据库的SELECT语句 – Profo 2012-02-08 15:06:34

+0

@Profo我编辑我的答案,如果你不需要一个可写的数据库。 – 2012-02-08 15:07:59