Objective-C /无法在“Resources”文件夹中访问(读取)文件

时间:2011-04-24 19:56:00

标签: objective-c ios4 file-manager

这可能是一个非常容易解决的问题,但我还没有成功。我已经将文件“questions_famquiz_easy_110326.txt”复制到资源文件夹,现在想要访问(读取)它和NSLog它以查看我能够读取它。

以下代码来自我根据我在网络上找到的示例所做的其中一项测试。

我正在尝试访问Resources文件夹中的txt文件而无法执行此操作。我已经搜索了一个解决方案,测试了很多,但没有成功。

我正在使用以下代码进行测试:

NSLog(@"\n \n >>>>>>viewDidLoad<<<<<<<<<");

NSError *error;

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:@"questions_famquiz_easy_110326.txt"];

if(![fileManager fileExistsAtPath:filePath])
{
    NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/questions_famquiz_easy_110326.txt"]];
    [data writeToFile:filePath atomically:YES];
}

NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"myString: %@", myString);

NSLog(@"\n \n>>>>>>DONE WITH viewDidLoad<<<<<<<<<");

exit(0);  //====EXIT JUST FOR THE TEST====<<<

上面的代码位于第一个启动的viewController中。

我得到的输出是:

>>>>>>viewDidLoad<<<<<<<<<
2011-04-24 21:53:47.825 FamQuiz_R0_1[542:307] myString: (null)
2011-04-24 21:53:51.044 FamQuiz_R0_1[542:307] 
>>>>>>DONE WITH viewDidLoad<<<<<<<<<

有人能帮助我解决这个问题吗?

更新

这是filePath:

2011-04-24 22:38:08.562 FamQuiz_R0_1[637:307] filePath: /var/mobile/Applications/7F5FDB03-0D22-46BC-91BC-4D268EB4BBEB/FamQuiz_R0_1.app/questions_famquiz_easy_110326.txt

这是我放置文件的地方: enter image description here

问题已解决:

NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

当我使用上述内容时,它不起作用,当我使用下面的工作并打印出文本时。

NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];

1 个答案:

答案 0 :(得分:1)

您没有从资源文件夹中读取内容。您正试图从文档目录中读取。所以回到零是有道理的,因为那里不存在文件。

变化:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:@"questions_famquiz_easy_110326.txt"];

为:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"questions_famquiz_easy_110326" ofType:@"txt"];

它应该适合你。