Monday, May 20, 2013

NSString writeToFile example ios

writeToFile: atomically: encoding: error:

Writes the contents of the receiver to a file at a given path using a given encoding.
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFileencoding:(NSStringEncoding)enc error:(NSError **)error
Parameters of [NSString writeToFile]
path
The file to which to write the receiver. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
enc
The encoding to use for the output.
error
If there is an error, upon return contains an NSError object that describes the problem. If you are not interested in details of errors, you may pass in NULL.
Return Value
YES if the file is written successfully, otherwise NO (if there was a problem writing to the file or with the encoding).
Discussion of [NSString writeToFile]
This method overwrites any existing file at path.
This method stores the specified encoding with the file in an extended attribute under the name com.apple.TextEncoding. The value contains the IANA name for the encoding and the CFStringEncoding value for the encoding, separated by a semicolon. The CFStringEncoding value is written as an ASCII string containing an unsigned 32-bit decimal integer and is not terminated by a null character. One or both of these values may be missing. Examples of the value written include the following:[NSString writeToFile]
MACINTOSH;0
UTF-8;134217984
UTF-8;
;3071
Example of [NSString writeToFile]
NSError *error = nil;
 BOOL ok = [hello_world writeToFile:filePath atomically:YES 
                        encoding:NSASCIIStringEncoding error:&error];
 if (error) {
      NSLog(@"Fail: %@", [error localizedDescription]);
 }
Example of [NSString writeToFile]
NSString * xmlData = @"This is some random string";
NSString * xmlString = [NSString stringWithString:xmlData];
NSError * error = nil;
if (![xmlString writeToFile:@"data.txt"
                 atomically:NO
                   encoding:NSASCIIStringEncoding
                      error:&error])
{
    NSLog(@"writeToFile failed: %@", error);
}
Example of [NSString writeToFile]
NSString *zStr = [aString stringValue];
NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
NSString *fileName = @"data.txt";
NSString *filePath = [directory stringByAppendingPathComponent:fileName];
[zStr writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];