Reading Text File from Xcode Bundle

。_饼干妹妹 提交于 2019-12-23 14:19:40

问题


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

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?

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

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


回答1:


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

Make sure your rtf file is copied into your resource.

Secondly, you're only getting the path of the rtf, and not the contents of the 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.




回答2:


First check that your file is present inside the bundle or not and if it present it must have same name as "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.



来源:https://stackoverflow.com/questions/12995661/reading-text-file-from-xcode-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!