从 Xcode Bundle 中读取文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12995661/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:53:23  来源:igfitidea点击:

Reading Text File from Xcode Bundle

objective-cxcodemacosfilebundle

提问by zakton

Why can't I read the content of foo.rtf? I've already put it in Xcode bundle. fileRoot still contains null.

为什么我看不到 foo.rtf 的内容?我已经把它放在 Xcode 包中了。fileRoot 仍然包含空值。

NSString* filePath = @"foo";
NSString* fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:@"rtf"];       

NSLog(@"File root contains %@", fileRoot);


@TheAmateurProgrammer, Thank you for the diagram. I just added foo.rtf into the bundle resources. The result for fileRoot is still null. What step am I still missing?

@TheAmateurProgrammer,谢谢你的图表。我刚刚将 foo.rtf 添加到捆绑资源中。fileRoot 的结果仍然为空。我还缺少哪一步?

Target's "Copy Bundle Resources" in Build Phases now contains foo.rtf. (I can't insert picture as I'm still a newbie).

Target 在 Build Phases 中的“Copy Bundle Resources”现在包含 foo.rtf。(由于我还是新手,无法插入图片)。

(I will add the content reading after I can get fileRoot to point correctly).

(我会在让 fileRoot 正确指向后添加内容阅读)。

回答by TheAmateurProgrammer

You added the file, but is it really copied to your application bundle?

您添加了文件,但它真的复制到您的应用程序包中了吗?

Make sure your rtf file is copied into your resource.

确保您的 rtf 文件已复制到您的资源中。

Secondly, you're only getting the path of the rtf, and not the contents of the rtf.

其次,你只得到了 rtf 的路径,而不是 rtf 的内容。

NSString *fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:@"rtf"]; 
NSString *contents = [[[NSAttributedString alloc] initWithRTF:[NSData dataWithContentsOfFile:fileRoot] documentAttributes:NULL] string];

That will get the contents of the rtf.

这将获得 rtf 的内容。

回答by kidsid49

First check that your file is present inside the bundle or not and if it present it must have same name as "foo.rtf".

首先检查您的文件是否存在于包中,如果存在,它必须与“foo.rtf”具有相同的名称。

You are getting nil because your file is not present directly inside in the bundle.

你得到零是因为你的文件没有直接存在于包中。

once you get the right file path you can get the content of your text file as a string by calling initWithContentsOfFile method on NSString class.

获得正确的文件路径后,您可以通过调用 NSString 类上的 initWithContentsOfFile 方法以字符串形式获取文本文件的内容。