开发者

How to read a .txt file in Xcode 4 (iPhone App) correctly

I'm trying to read a .txt(test) file into a TextView (testText) :

-(void)viewDidLoad {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
    if (filePath) {
        NSString *contentOfFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        testText.text = contentOfFile;
    }
    [filePath release];
}

Yes the file is in the Supporting Files directory. I also tried some "similar" actions like "initWithContentOfFile" etc. but I got three diffe开发者_StackOverflow社区rent errors: 1. SIGABRT 2. EXEC_BAD_ACCESS 3. It is reading the text but adds a lot of additional data it shouldn't display in the testText like {colortbl;red255 green 255 blue 255;margl1440.... and so on.

Am I doing it wrong? Well, certainly because it doesn't work, but at which part do I fail? The original text in the file is "This is a test. Finally it works!" its displayed too but only after a lot of strange additional text.


Firstly, don't call [filePath release];. -pathForResource:ofType: will return an autoreleased string, so you shouldn't release it again.

The {colortbl;red255... text indicates that your file is actually an RTF file. It might be named .txt, but it is really RTF. You need to create a plain text file (in TextEdit you can choose Format > Make Plain Text to do this).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜