"Write NSString to file"

Mon 14 June 2010

 

//Method writes a string to a text file

-(void) writeToTextFile{

//get the documents directory:

NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:

NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt"

  documentsDirectory];

//create content - four lines of text

NSString *content = @"One\nTwo\nThree\nFour\nFive";

//save content to the documents directory

[content writeToFile:fileName 

  atomically:NO 

encoding:NSStringEncodingConversionAllowLossy 

  error:nil];

}