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:
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
}
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:
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];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…