如何在 Xcode 4(iPhone 应用程序)中正确读取 .txt 文件
我正在尝试将 .txt(test) 文件读入 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];
}
是的,该文件位于支持文件目录中。 我还尝试了一些“类似”的操作,例如“initWithContentOfFile”等,但我收到了三个不同的错误: 1.SIGABRT 2. EXEC_BAD_ACCESS 3. 它正在读取文本,但添加了许多不应在 testText 中显示的附加数据,例如 {colortbl;red255 green 255 blue 255;margl1440.... 等等。
我做错了吗?嗯,当然是因为它不起作用,但是我在哪一部分失败了呢?文件中的原文是“这是一个测试。终于成功了!”它也显示,但只有在很多奇怪的附加文本之后才显示。
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 different 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,不要调用
[filePath release];
。-pathForResource:ofType:
将返回一个自动释放的字符串,因此您不应再次释放它。{colortbl;red255...
文本表示您的文件实际上是 RTF 文件。它可能被命名为.txt
,但它实际上是 RTF。您需要创建一个纯文本文件(在 TextEdit 中,您可以选择“格式”>“制作纯文本”来执行此操作)。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).