0

I'm trying to write a csv file. I have two arrays at hand - one with the titles (Name, Number etc), another with the actual values (Jon, 123 ...).

Now, after the following two operations:

[[titles componentsJoinedByString:@", "] writeToFile:file atomically:YES];

[[values componentsJoinedByString:@", "] writeToFile:file atomically:YES];

only the values array is written to the file. I realise that I may need to open the file again, but how do I do that after writing the first array? Or what is it exactly that I'm doing wrong if this is not the case?

Thanks!

Sorin Cioban
  • 2,237
  • 6
  • 30
  • 36

2 Answers2

1

The second line is in fact overwriting the file you wrote in the first line. One simple way to get around this problem would be to simply append the second string to the first (likely with an '\n' in between since you're making a csv file) and writing that string to your file:

NSString *str1 = [[titles componentsJoinedByString:@", "];
NSString *str2 = [[values componentsJoinedByString:@", "];
NSString *outputStr = [str1 stringByAppendingFormat:@"\n%@", str2];
[outputStr writeToFile:file atomically:YES];
Sean
  • 5,810
  • 2
  • 33
  • 41
  • Thanks :) I knew I was missing something. So in conclusion, is it not possible to use "writeToFile:atomically" twice on the same file? – Sorin Cioban May 11 '12 at 12:37
0

Second time it replaces the old contents. So you could read the old content, append the old content with the new content and save on file.

Write first row

[[titles componentsJoinedByString:@", "] writeToFile:file atomically:YES];

Where you need to add another row every time

NSString *previousContent = [[NSString alloc] initWithContentsOfFile:file usedEncoding:nil error:nil];
NSString *str2 = [[values componentsJoinedByString:@", "];
NSString *outputStr = [previousContent stringByAppendingFormat:@"\n%@", str2];
[outputStr writeToFile:file atomically:YES];
Warif Akhand Rishi
  • 23,920
  • 8
  • 80
  • 107