开发者

Cocoa: basic problem getting string from file

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 docu开发者_开发技巧mentation 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.


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"


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜