NSUTF8StringEncoding导致文件在TextEdit / Pages中不正确地呈现,而不是BBEdit / vi [英] NSUTF8StringEncoding causes file to render improperly in TextEdit/Pages, but not BBEdit/vi

查看:111
本文介绍了NSUTF8StringEncoding导致文件在TextEdit / Pages中不正确地呈现,而不是BBEdit / vi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个怪异的问题。每当我在我的iOS应用程序中创建一个新的文本文件,我设置其编码为 NSUTF8StringEncoding 。如果我编辑文件并输入任何带有变音符号的字符并保存更改,变音符号在某些应用程序(如BBEdit,TextMate,cat和vi)中正确显示,但在其他应用程序(如TextEdit,Quick Look和Pages)中不正确显示。

I'm running into a bit of a weird issue. Whenever I create a new text file in my iOS application, I set its encoding to be NSUTF8StringEncoding. If I edit the file and input any characters with diacritics and save the changes, the diacritics render properly in some applications such as BBEdit, TextMate, cat and vi but not in others such as TextEdit, Quick Look and Pages.

我使用下面的代码将UITextView的内容保存到纯txt文件中。

I'm using the following code to save the contents of a UITextView to the plain txt files.

  NSError *error;
  NSString *dataString = self.textView.text;
  BOOL savedChanges = [dataString writeToFile:fullPath atomically:YES encoding:NSUTF8Encoding error:&error]; 
  if (!savedChanges)
  {
    // Pop up an alert saying something went wrong.
  }

unix 命令报告保存的文件确实是UTF-8 Unicode文本,没有行终止符

The unix file command reports that the saved file is indeed "UTF-8 Unicode text, with no line terminators"

甚至更糟糕的是,如果我保存文件,而不更改文本的内容,则文件将在Quick Look& TextEdit在我的Mac上。

What's even weirder is if I save the file again without changing the contents of the text, the file will then render properly in Quick Look & TextEdit on my Mac.

任何帮助将不胜感激。

推荐答案

如果您使用UTF BOM保存文本文件,并且未设置 com.apple.TextEncoding xattr,任何打开它的软件都必须猜测正确的字符编码。一些应用程序猜测UTF-8,一些猜测Mac OS罗马,和其他人猜测别的东西。

If you save a text file with an UTF BOM, and the com.apple.TextEncoding xattr is not set, any software that opens it will have to guess at the correct character encoding. Some apps guess UTF-8, some guess Mac OS Roman, and others guess something else.

您可以通过将文件保存为UTF-8而不使用BOM来复制此行为,然后在Terminal中给出 xattr -d com.apple .textEncoding filename.txt 命令。

You can replicate this behavior by saving a file as UTF-8 with no BOM, and then in Terminal give the xattr -d com.apple.TextEncoding filename.txt command.

要设置xattr,您需要调用setxattr()。似乎没有一个文档化的方式通过Cocoa API来设置它。您还可以在数据前添加UTF-8 BOM。

To set the xattr, you would call setxattr(). There doesn't seem to be a documented way to set it via a Cocoa API. You could also prefix your data with the UTF-8 BOM.

当BOM和xattr丢失时,应该假设什么字符编码。这是一个错误,如果它默认为Mac OS罗马? UTF-8是否应该是默认值?

There's the question of what character encoding should be assumed when the BOM and xattr are missing. Is it a bug if it defaults to Mac OS Roman? Should UTF-8 be the default?

这篇关于NSUTF8StringEncoding导致文件在TextEdit / Pages中不正确地呈现,而不是BBEdit / vi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆