fileHandleForUpdatingURL :error:
Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL.
Parameters
- url
- The URL of the file, device, or named socket to access.
- error
- If an error occurs, upon return contains an
NSError
object that describes the problem. PassNULL
if you do not want error information.
Return Value of [NSFileHandle fileHandleForUpdatingURL]
The initialized file handle object or
nil
if no file exists at url.Discussion of [NSFileHandle fileHandleForUpdatingURL]
The file pointer is set to the beginning of the file. The returned object responds to both
NSFileHandle
read...
messages and writeData:
.
When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.
Example of [NSFileHandle fileHandleForUpdatingURL]
- (void)saveText:(NSString *)text append:(BOOL)append
{
NSError *error = nil;
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingURL:filePathURL error:&error];
if (error) {
[fileHandle closeFile];
[delegate fileManagerFailWithError:error];
} else {
if (append) {
[fileHandle seekToEndOfFile];
} else {
[fileHandle truncateFileAtOffset:0];
}
[fileHandle writeData:data];
[fileHandle closeFile];
[delegate fileManagerDidSaveText:text];
}
}