gpt4 book ai didi

cocoa-touch - NSFileHandle fileHandleForWritingAtPath : return null!

转载 作者:行者123 更新时间:2023-12-03 07:53:54 26 4
gpt4 key购买 nike

我的 iPad 应用程序有一个小的下载工具,我想使用 NSFileHandle 附加数据。问题是创建调用只返回空文件句柄。可能是什么问题呢?这是应该创建我的文件句柄的三行代码:

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];

我检查了文件路径,没有发现任何问题。

TYIA

最佳答案

fileHandleForWritingAtPath不是“创造”电话。文档明确指出:“返回值:初始化的文件句柄,或 如果路径 中不存在文件,则为零”(强调)。如果您希望在文件不存在的情况下创建该文件,则必须使用以下内容:

 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
}

如果要附加到文件(如果文件已经存在),请使用类似 [output seekToEndOfFile] 的内容。 .您的完整代码如下所示:
 NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
} else {
[output seekToEndOfFile];
}

关于cocoa-touch - NSFileHandle fileHandleForWritingAtPath : return null!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com