ios 目标 C:读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5043864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective C: Reading text files
提问by Chris
I've done this before, but its not working for me now. I'm doing:
我以前这样做过,但现在对我不起作用。我正在做:
NSString* path = [[NSBundle mainBundle] pathForResource:@"test"
ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSLog(@"%@",path);
and it returns (null)
every time when I NSLog path and content. Can anyone see what I'm doing wrong?
(null)
每次我 NSLog 路径和内容时它都会返回。谁能看到我做错了什么?
采纳答案by Tommy
content will be nil (which logs as '(null)') if you pass it a path it can't open. So your only issue is that the relevant instance of NSBundle is unable to find test.txt within the resources part of your application bundle.
如果您传递给它无法打开的路径,则内容将为 nil(记录为 '(null)')。因此,您唯一的问题是 NSBundle 的相关实例无法在应用程序包的资源部分中找到 test.txt。
You should:
你应该:
- check the file is in your Xcode project; and, if it is,
- check it's included in the 'Copy Bundle Resources' phase underneath your selected Target (in the project tree view on the left in the normal Xcode window layout) and, if it is,
- look inside the generated application bundle (find your product, right click, select 'Reveal in Finder', from Finder right click on the app and select 'Show Package Contents', then look for your file in there) to make sure that it's there.
- 检查文件是否在您的 Xcode 项目中;并且,如果是,
- 检查它是否包含在所选目标下方的“复制捆绑资源”阶段(在正常 Xcode 窗口布局左侧的项目树视图中),如果是,
- 查看生成的应用程序包(找到您的产品,右键单击,选择“在 Finder 中显示”,从 Finder 中右键单击应用程序并选择“显示包内容”,然后在其中查找您的文件)以确保它在那里.
If it's copied in but the relevant instance of NSBundle can't find it then something very strange is afoot.
如果它被复制进来,但 NSBundle 的相关实例找不到它,那么一些非常奇怪的事情正在发生。