1

I am trying to write NSString to the file. It is writing successfully however I want to append the new string to new line.

How can do this?

Maksim
  • 2,054
  • 3
  • 17
  • 33
user968597
  • 1,164
  • 2
  • 15
  • 30

1 Answers1

1

You can read file content, append new data to that content and save new data to a file you use:

// Here you set your appending text.    
NSString *yourAppendingText = @"yourAppendingText";  

// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:@"yourFile.txt"];

// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
Maksim
  • 2,054
  • 3
  • 17
  • 33