Saturday, April 27, 2013

NSFileHandle fileHandleForUpdatingAtPath example ios


fileHandleForUpdatingAtPath:

Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified path.
+ (id)fileHandleForUpdatingAtPath:(NSString *)path
Parameters
path
The path to the file, device, or named socket to access.
Return Value of [NSFileHandle fileHandleForUpdatingAtPath]
The initialized file handle object or nil if no file exists at path.
Discussion of [NSFileHandle fileHandleForUpdatingAtPath]
The file pointer is set to the beginning of the file. The returned object responds to both read... messages andwriteData:.
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 fileHandleForUpdatingAtPath]

- (void)saveText:(id)sender
{
    [self.textview resignFirstResponder];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
    NSString *savedString = textview.text;

    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:documentTXTPath ];
    [myHandle seekToEndOfFile];
    [myHandle writeData:  [savedString dataUsingEncoding:NSUTF8StringEncoding]];
    [myHandle closeFile];

}