Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a new line of a file in Objective-C

For some strange reason, the \n and \r escape sequences do not seem to be working in my code. I want to write each NSString on a new line of the file, but it just appends it the last string on one line. Here's the code:

for (Entry *entry in self.entries) {
    NSString *path = @"/Users/me/File.txt";
    NSString *string = (@"%@\r\n", [entry thisEntry]);
    NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:path];
    [fh seekToEndOfFile];
    [fh writeData:[string dataUsingEncoding:NSUnicodeStringEncoding]];
    [fh closeFile];
}

Am I doing something wrong? Forgive me as I am new to Objective-C.

like image 285
Kulpreet Avatar asked Dec 12 '22 22:12

Kulpreet


1 Answers

Your problem is this:

NSString *string = (@"%@\r\n", [entry thisEntry]);

It should be:

NSString *string = [NSString stringWithFormat:@"%@\r\n", [entry thisEntry]];
like image 175
Dave DeLong Avatar answered Jan 19 '23 01:01

Dave DeLong