1

I want to write the contents of an array to a text file in my iPhone application. I can load the array from the text file but i want to allow deleting of content through the array and again write the contents to the text file. How can I achieve this? Or simply if anyone can guide me how to delete the last word of a text file would also be helpful.
EDIT :- basically i want to delete the last word in a text file. can you help me with the logic to achieve that .

Bonnie
  • 4,943
  • 30
  • 34

3 Answers3

4

Write the contents of your original array as shown below:

[firstArray writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];

Whenever you want to retrieve and modify the array, retrieve the contents of the file int an NSMutableArray:

NSMutableArray *myArr = [NSMutableArray arrayWithContentsOfFile:@"/Users/sample/Untitled.txt"];
[myArr removeLastObject];  //Any modification you wanna do
[myArr writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];
Shanti K
  • 2,873
  • 1
  • 16
  • 31
  • 2
    its stored in this format ` one two three ` – Bonnie Jan 06 '12 at 07:31
  • @Bonnie, the format is OK, the other method in the answer reads it back in as an array of strings. Unless you need the file to be in a particular format? – jrturton Jan 06 '12 at 07:35
  • @jrturton , i need it to be in plain text format, for using it further, basically i want to delete the last word in a text file. can you help me achieve that – Bonnie Jan 06 '12 at 09:11
2

There is method in NSArray to write the array into a file.

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Please check the Apple documentation

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
  • thanks that helped a little but the array is written in xml format here's how it is saved



    one
    two three
    i only want the string to be written, will i have to use an xml parser ? its much more trouble, is there a workaround ?
    – Bonnie Jan 06 '12 at 07:25
2

the approach in other answers works bu the file is written in a XML format. to simply write the contents of the array in a text file , I first Appended all the strings of the array into a large string then write that string into the text file .below is the code i used for that

NSString *stringToWrite=[[NSString alloc]init];

for (int i=0; i<[stringArray count]; i++)

{
stringToWrite=[stringToWrite stringByAppendingString:[NSString stringWithFormat:@"%@ ",[stringArray objectAtIndex:i]]];

}

[stringToWrite writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

this will write the contents of the array in plain text format.

Bonnie
  • 4,943
  • 30
  • 34