NSFileHandle fileHandleForWritingAtPath:返回null!

Jea*_*uys 35 cocoa-touch nsfilehandle

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

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

我检查了文件路径,我没有看到任何错误.

TYIA

Rap*_*ert 85

fileHandleForWritingAtPath不是"创造"的召唤.文档明确指出:"返回值:初始化文件句柄,如果路径中不存在文件,则为nil "(强调添加).如果你想创建文件,如果它不存在,你必须使用这样的东西:

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

如果要附加到文件(如果已存在),请使用类似的内容[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];
 }
Run Code Online (Sandbox Code Playgroud)