Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

cocoa touch - NSFileHandle fileHandleForWritingAtPath: return null!

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

question from:https://stackoverflow.com/questions/3664362/nsfilehandle-filehandleforwritingatpath-return-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...