Saturday, April 27, 2013

NSFileHandle fileHandleForUpdatingURL example ios


fileHandleForUpdatingURL :error:

Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL.
+ (id)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error
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. Pass NULL 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 NSFileHandleread...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];
    }
    
}