I am fairly new to iphone development and programming in general and am wondering how to read some text from a text file to be diplayed in a UITextView. I have tried various ways to do it but just can't seem to be able to get it to display:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"];
NSString *someText=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
textView.text=someText;
Some sample code would be greatly appreciated. Th开发者_如何学编程anks in advance
You shouldn't include the extension in the pathForResource:
parameter:
[[NSBundle mainBundle] pathForResource:@"untitled.txt" ofType:@"txt"]
should be
[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"]
.
I had to change the name of the text file to 'untitled.txt' from just plain 'untitled' in Xcode. It was a text file but didn't have the extension of .txt
. This doesn't seem to be automatically appended if you create the text file in Xcode.
Is untitled.txt
actually where you think it is? Try logging filePath
and see if it's what you expect. (You could do [[NSFileManager defaultManager] isReadableFileAtPath:filePath]
to be completely certain.)
If the path is correct then the problem must be with loading the text. One such problem could be that the file is not encoded in UTF8. Mike Ash recently blogged about character encoding. At the end of the post he describes how to handle text files of unknown encoding.
精彩评论