Objective C: Reading text files

Objective CIosTextBundle

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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.

You should:

  1. check the file is in your Xcode project; and, if it is,
  2. 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,
  3. 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.

If it's copied in but the relevant instance of NSBundle can't find it then something very strange is afoot.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - Objective CTommyView Answer on Stackoverflow