首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >[NSBundle mainBundle]pathForResource返回空

[NSBundle mainBundle]pathForResource返回空
EN

Stack Overflow用户
提问于 2012-06-18 18:32:23
回答 4查看 3.7K关注 0票数 0

我正在尝试将我的应用程序连接到SQLite数据库,但收到的消息告诉我数据库已创建,但没有表。

我调试了程序,发现[[NSBundle mainBundle] pathForResource]总是返回nil

代码语言:javascript
复制
NSString* file = [[NSBundle mainBundle]pathForResource:_databaseName ofType:_databaseType];

为什么会发生这种情况?请帮帮我!

EN

回答 4

Stack Overflow用户

发布于 2012-06-18 18:40:35

首先:确保您的数据库在应用程序包中。

然后,您需要实现将路径复制到文档目录.as的方法

代码语言:javascript
复制
-(NSString *) getDBPath:(NSString*)databaseName {
// search for the existed paths
NSArray *paths = NSSearchPathForDirectoriesInDomains(  NSDocumentDirectory , NSUserDomainMask, YES);
  NSString *documentsDir = [paths objectAtIndex:0];


return [documentsDir stringByAppendingPathComponent:databaseName];

}

代码语言:javascript
复制
- (void) InstantiateYourDatabase:(NSString *)DatabaseName {


//Using NSFileManager we can perform many file system operations.

NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *error;
NSString *dpname=DatabaseName;

_dbPath = [self getDBPath:dpname];

BOOL success = [fileManager fileExistsAtPath:_dbPath];

NSLog(@"success == %i",success);

if( !success) {

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
                               stringByAppendingPathComponent:DatabaseName];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:_dbPath error:&error];

}  

}

告诉我这有没有帮助!

票数 1
EN

Stack Overflow用户

发布于 2012-06-18 18:35:55

尝试使用以下代码查找数据库路径

代码语言:javascript
复制
    NSString *databaseName = @"your_db_name.sql";
    NSString *databasePath;
    // Get the path to the documents directory and append the databaseName
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    NSLog(@"Database Path is: %@",databasePath);

您想了解有关iOS中Sqllite数据库连接的更多详细信息,请尝试此tutorial

欢迎!

票数 0
EN

Stack Overflow用户

发布于 2012-06-18 18:47:36

如果您创建了一个sqlite db文件并将其拖到xcode3中的项目中,则它在运行时位于应用程序文档文件夹中。

代码语言:javascript
复制
NSString *databaseName = @"cartoon.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentDir stringByAppendingPathComponent:databaseName];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11081041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档