在Objective-C中写入文件的新行
出于某种奇怪的原因,\n和\r转义序列在我的代码中似乎不起作用。我想将每个NSString写在文件的新行上,但它只是将最后一个字符串附加在一行上。代码如下:在Objective-C中写入文件的新行,objective-c,escaping,nsfilehandle,Objective C,Escaping,Nsfilehandle,出于某种奇怪的原因,\n和\r转义序列在我的代码中似乎不起作用。我想将每个NSString写在文件的新行上,但它只是将最后一个字符串附加在一行上。代码如下: for (Entry *entry in self.entries) { NSString *path = @"/Users/me/File.txt"; NSString *string = (@"%@\r\n", [entry thisEntry]); NSFileHandle *fh = [NSFileHandl
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];
}
我做错什么了吗?请原谅,我是Objective-C的新手。您的问题是:
NSString *string = (@"%@\r\n", [entry thisEntry]);
应该是:
NSString *string = [NSString stringWithFormat:@"%@\r\n", [entry thisEntry]];
是的!就是这样……似乎工作得很好。看来我犯了个愚蠢的错误。再次感谢!