Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c Cocoa:从文件中获取字符串的基本问题_Objective C_Cocoa_String_File - Fatal编程技术网

Objective c Cocoa:从文件中获取字符串的基本问题

Objective c Cocoa:从文件中获取字符串的基本问题,objective-c,cocoa,string,file,Objective C,Cocoa,String,File,是否有一些显而易见的原因导致生成一个nil字符串而不是文件的实际文本内容 NSString *fromFile = [NSString stringWithContentsOfFile: @"file://localhost/Users/username/Desktop/test.txt"]; NSLog(@"%@", fromFile); PRINTS: "(null)" 该文件是从TextWrangler保存的纯ASCII文本文件,内容为“

是否有一些显而易见的原因导致生成一个nil字符串而不是文件的实际文本内容

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

NSLog(@"%@", fromFile);

PRINTS: "(null)"
该文件是从TextWrangler保存的纯ASCII文本文件,内容为“abc”

路径来自将实际文件从桌面拖动到Xcode编辑器窗口

我也试过不用“file://localhost“

方法文档说明“如果文件无法打开,则返回nil”。文件没有什么异常(未锁定等)。它具有默认的Unix权限,由运行Xcode的同一用户创建


我知道这种方法已经被弃用了——首先尝试让它工作。

您是否尝试过
~/Desktop/test.txt
/username/Desktop/test.txt

您将
stringWithContentsOfFile:
stringWithContentsOfURL:
混为一谈了

如果您正在传递URL,例如

@"file://localhost/Users/username/Desktop/test.txt“
您需要
stringWithContentsOfURL:
并将参数设为
NSURL
[NSURL URLWithString:@”file://localhost/Users/username/Desktop/test.txt“]

如果要使用
stringWithContentsOfFile:

@/Users/username/Desktop/test.txt“

我想我肯定有三次了。现在/Users/username/Desktop/test.txt确实在工作。但是顺便说一句~/Desktop/test.txt不起作用。您可能需要调用NSString的stringByExpandingTildeInPath方法才能使第二个方法起作用,对此表示抱歉。奇怪的是“file://localhost/...“如果将文件本身拖动到Xcode编辑器窗口中,则Xcode将生成该文件。/Users/。。。路径确实有效。。。谢谢。请注意,stringWithContentsOfURL似乎不适用于“file://localhost“要么——产生关于不同Objective-C类型(??)的警告。啊,误读了文档-参数是一个NSURL-为此进行了编辑-但是总是测试代码;(哦,天哪,它在没有file://localhost 部分--@“/Users/username/Desktop/testabc3.txt”。无需担心:|我投票删除整个问题!对不起,你只能像我们其他人一样忍受公众的羞辱。其他人可能也会有同样的问题。