读取文件夹中的文本文件
我正在开发一个 iPhone 应用程序。
我知道如何读取与项目位于同一目录中的文本文件。 但是如何读取与项目位于同一目录中的文件夹中的文件呢? 它总是给我一个空白屏幕。
这有效:
NSString *textUrl = [[NSBundle mainBundle] pathForResource:@"myText" ofType:@"txt"];
textView.text = [NSString stringWithContentsOfFile:textUrl encoding:NSUTF8StringEncoding error:nil];
但这给了我一个空白的文本视图:
NSString *textUrl = [[NSBundle mainBundle] pathForResource:@"myFolder/myText" ofType:@"txt"];
textView.text = [NSString stringWithContentsOfFile:textUrl encoding:NSUTF8StringEncoding error:nil];
我该如何解决这个问题?
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.
This works:
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];
How do I resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
读取文件与开发机器硬盘上的文件结构无关。它与目标设备硬盘的文件结构有关。如果您查看标准 iOS 应用程序 Xcode 项目的构建阶段,您将看到“复制捆绑资源”阶段。此阶段负责将资源(例如文本文件)复制到应用程序的文档目录。
即使您的资源位于开发计算机项目结构中的不同文件夹中,也很有可能将其复制到应用程序包中的根级文档目录中。您可以通过查看“复制捆绑资源”构建阶段并检查您要加载的资源来获得想法。如果它不在文件夹引用(蓝色的 Finder 式文件夹)中,则它可能只是被复制到根级别。
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.
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.
NSBundle 具有方法 pathForResource:ofType:inDirectory:
NSBundle has the method pathForResource:ofType:inDirectory: