NSFileHandle fileHandleForWritingAtPath:返回 null!
我的 iPad 应用程序有一个小型下载工具,我想使用 NSFileHandle 附加数据。问题是创建调用仅返回空文件句柄。可能是什么问题?这是应该创建文件句柄的三行代码:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
我检查了文件路径,没有发现任何问题。
泰亚
my iPad app has a small download facility, for which I want to append the data using an NSFileHandle. The problem is the creation call only returns null file handles. What could be the problem? Here is the three lines of code that are supposed to create my file handle:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
I checked the file path, and I could see nothing wrong.
TYIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fileHandleForWritingAtPath
不是“创建”调用。文档明确指出:“返回值:初始化的文件句柄,如果路径中不存在文件,则nil”(添加了强调)。如果您希望在文件不存在的情况下创建该文件,则必须使用类似以下的内容:如果您想追加到该文件(如果它已存在),请使用类似
[outputeekToEndOfFile]
的内容。您的完整代码将如下所示:fileHandleForWritingAtPath
is not a “creation” call. The documentation explicitly states: “Return Value: The initialized file handle, or nil if no file exists at path” (emphasis added). If you wish to create the file if it does not exist, you’d have to use something like this:If you want to append to the file if it already exists, use something like
[output seekToEndOfFile]
. Your complete code would then look as follows:获取文档目录路径
将文本保存到文件末尾
如果文件不存在,则创建该文件并
使用指定的文件名写入数据从文件中获取文本
>删除文件
Get documents directory path
Save text to end of the file
if file doesnt exist create it and write data
get text from file with specified filename
Delete file
初始化程序 API 已更改,但这对其他人来说仍然可能有用。
我正在使用
FileHandle(forReadingAtPath: String)
初始化程序,当我意识到:fileURL.absoluteString
作为路径时,初始化程序返回nil
(绝对字符串看起来像 file:///Users/xyz/Library/.../Containers/Data/Application/...file.MP4/Users/xyz/Library/.../Containers/Data/Application/...file.MP4
)基本上,
FileHandler
初始化程序更喜欢相对路径而不是绝对字符串。The initialiser APIs have changed, but this still might be useful for other people.
I was using the
FileHandle(forReadingAtPath: String)
initialiser, when I realised that:nil
while usingfileURL.absoluteString
for the path (absolute string looks likefile:///Users/xyz/Library/.../Containers/Data/Application/...file.MP4
fileURL.relativePath
for the path. (relative path looks like/Users/xyz/Library/.../Containers/Data/Application/...file.MP4
)Basically, the
FileHandler
initialiser prefers the relative path over the absolute string.