开发者

Different encoding results when using writeToFile:atomically:encoding:error: vs. createFileAtPath:contents:attributes:

In my iPhone App I have the capability to export data to an .txt file and send it via Mail – but have currently problems regarding the encoding.

To attach the file to mail I simply create a NSData instance from a NSString instance as followed:

NSData *dataToExport = [[NSData alloc] initWithData:[myExportString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSFileManager defaultManager] createFileAtPath:pathToExportFile contents:dataToExport开发者_运维问答 attributes:nil];

But this finally results in a file with content like that (wrong encoding):

√úberraschung

Instead using

[myExportString writeToFile:pathToExportFile atomically:NO encoding:NSUTF8StringEncoding error:&error];

... creates a file with the correct enconding:

Überraschung

Any ideas, how I'm able to get the right encoding with the first way?

Thank you, Florian


NSString's writeToFile:atomically:encoding:error: method sets an extended attribute on the output file identifying the encoding. TextEdit checks for this attribute and uses that encoding when it's present.

Since you don't (and can't) tell NSFileManager's method what encoding to use (since it's for plain data, not necessarily text encoded as data), it won't set this attribute. Without it, TextEdit will guess, and it does so quite poorly.

I don't know whether MobileMail will preserve the extended attribute somehow. Try it both ways, and when you receive the messages, check their raw contents and see whether one of them specifies the file's encoding. At any rate, your hex dumps prove that the text is being encoded correctly either way.

More generally, when you want to write out text to a file, NSString's methods are the correct solution.


That's strange. Here ist the hexdump -C output.

"Wrong" encoding:

00000000  c3 9c 62 65 72 72 61 73  63 68 75 6e 67           |..berraschung| 
0000000d

"Right" encoding:

00000000  c3 9c 62 65 72 72 61 73  63 68 75 6e 67           |..berraschung|
0000000d

I'm also trying different applications to view the documents:

  • TextEdit: wrong
  • Excel: wrong
  • SubEthaEdit: right
  • Numbers: right

Very strange,right?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜