问题描述
我正在开发iPhone应用程序.
I'm developing an iPhone app.
我知道如何读取与项目位于同一目录中的文本文件.但是,如何读取与项目位于同一目录中的文件夹中的文件?它总是让我空白.
I know how to read a text file placed in the same directroy as the project.But how do I read files in a folder placed in the same directory as the project?It always gives me a blank screen.
这有效:
NSString *textUrl = [[NSBundle mainBundle] pathForResource:@"myText" ofType:@"txt"];
textView.text = [NSString stringWithContentsOfFile:textUrl encoding:NSUTF8StringEncoding error:nil];
但这给了我一个空白的文本视图:
But this gives me a blank text view:
NSString *textUrl = [[NSBundle mainBundle] pathForResource:@"myFolder/myText" ofType:@"txt"];
textView.text = [NSString stringWithContentsOfFile:textUrl encoding:NSUTF8StringEncoding error:nil];
我该如何解决?
推荐答案
读取文件与开发机硬盘上的文件结构无关.它与目标设备硬盘驱动器的文件结构有关.如果您查看标准iOS应用Xcode项目的构建阶段,则将看到复制捆绑资源"阶段.此阶段负责将资源(如文本文件)复制到应用程序的文档目录中.
Reading files has nothing to do with the file structure on the dev machine's hard drive. It has everything to do with the file structure of the target device's hard drive. If you look at the build phases for your standard iOS app Xcode project, you'll see a "Copy Bundle Resources" phase. This phase is responsible for copying resources (like your text file) to the app's documents directory.
很有可能,即使您的资源位于开发机器项目结构中的其他文件夹中,也仍将其复制到应用程序捆绑包中的根目录文档目录中.您可以通过查看副本捆绑资源"构建阶段并检查要加载的资源来获得想法.如果它不在文件夹引用中(蓝色,带有Finder风格的文件夹),则可能只是被复制到了根级别.
There's a decent chance that, even if your resource is in a different folder in your dev machine's project structure, it is still being copied to the root level documents directory in the app bundle. You can get an idea by looking in that Copy Bundle Resources build phase and check for the resource you're looking to load. If it's not in a folder reference (a blue, Finder-esque, folder) it's likely just being copied to the root level.
这篇关于读取文件夹中的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!