2

Is there some blindingly obvious reason why this is producing a nil string instead of the actual text content of the file?

NSString *fromFile = [NSString stringWithContentsOfFile:
                       @"file://localhost/Users/username/Desktop/test.txt"];

NSLog(@"%@", fromFile);

PRINTS: "(null)"

The file is a plain ASCII text file saved from TextWrangler with contents ' abc '.

The path comes from dragging the actual file from the desktop into the Xcode editor window.

I've also tried without "file://localhost".

The method documentation says "Returns nil if the file can't be opened". There's nothing unusual about the file (not locked, etc.). It has default Unix permissions and was created by the same user as is running Xcode.

I know this method is deprecated -- trying to get this working first.

3
  • Oh guh -- it IS working without the file://localhost part -- @"/Users/username/Desktop/testabc3.txt". Nevermind : | Commented Feb 23, 2010 at 14:27
  • I vote to delete this whole question! Commented Feb 23, 2010 at 14:28
  • 5
    Sorry, you'll just have to live the public shame just like the rest of us. Somebody else might have the same problem down the road. Commented Feb 23, 2010 at 15:13

2 Answers 2

4

You have stringWithContentsOfFile: and stringWithContentsOfURL: mixed up.

If you are passing in a URL e.g. @"file://localhost/Users/username/Desktop/test.txt" the you want stringWithContentsOfURL: and make the parameter a NSURL e.g. [NSURL URLWithString:@"file://localhost/Users/username/Desktop/test.txt"]

If you want to use stringWithContentsOfFile: the the parameter should be @"/Users/username/Desktop/test.txt"

Sign up to request clarification or add additional context in comments.

3 Comments

Strangely "file://localhost/..." is what Xcode produces if you drag the file itself into the Xcode editor window. The /Users/... path does work... Thanks.
Note that stringWithContentsOfURL doesn't seem to work with "file://localhost" either -- produces warning about distinct Objective-C type (??).
Ah misread the docs - the parameter is a NSURL - edited for that - however always test code ;(
0

Have you tried ~/Desktop/test.txt or /Users/username/Desktop/test.txt?

2 Comments

Well I thought I had, for sure, 3 times. And now indeed /Users/username/Desktop/test.txt is working. But BTW ~/Desktop/test.txt doesn't work.
you would probably need to call NSString's stringByExpandingTildeInPath method to make the second one work, sorry about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.