开发者

Read text file in a folder

I'm developing an iPhone app.

I know how to read a te开发者_StackOverflowxt 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?


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 has the method pathForResource:ofType:inDirectory:

NSString *textUrl = [[NSBundle mainBundle] pathForResource:@"myText" ofType:@"txt" inDirectory:@"myFolder"];
textView.text = [NSString stringWithContentsOfFile:textUrl encoding:NSUTF8StringEncoding error:nil];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜