63

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?

Chris
  • 6,863
  • 17
  • 64
  • 108
  • 4
    if path is nil that means your file name is incorrect for some reason - check if file actually copied to application bundle, then check if file name is really identical (remember that file system on iOS is case sensitive) – Vladimir Feb 18 '11 at 16:32
  • 1
    You're completely right, I just need someone to point it out. I named it text.txt instead of test.txt – Chris Feb 18 '11 at 16:33
  • i just want to make sure does test.txt file exist in your xcode project. – Robin Feb 18 '11 at 16:34

1 Answers1

49

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.

Tommy
  • 97,164
  • 12
  • 174
  • 193
  • 20
    That's because the comments weren't present yet when I wrote my answer, and the normal notification bar that StackOverflow gives you to warn if other answers has appeared while you've been typing isn't presented when new comments are posted. Launching Xcode and checking that I was directing Chris to the right places to check things obviously took at least 2 minutes. – Tommy Feb 18 '11 at 17:00