gpt4 book ai didi

cocoa - NSAttributedString initWithHTML 字符编码不正确?

转载 作者:行者123 更新时间:2023-12-03 16:01:58 26 4
gpt4 key购买 nike

-[NSMutableAttributedString initWithHTML:documentAttributes:] 似乎破坏了特殊字符:

NSString *html = @"“Hello” World"; // notice the smart quotes
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithHTML:htmlData documentAttributes:nil];
NSLog(@"%@", as);

打印“Hello”World,后跟一些RTF命令。在我的应用程序中,我将属性字符串转换为 RTF 并将其显示在 NSTextView 中,但其中的字符也被损坏。

根据文档,默认编码是UTF-8,但我尝试明确,结果是相同的:

NSDictionary *attributes = @{NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]};
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithHTML:htmlData documentAttributes:&attributes];

最佳答案

创建 NSData 时使用 [html dataUsingEncoding:NSUnicodeStringEncoding],并在将 HTML 解析为属性字符串时设置匹配的编码选项:

NSCharacterEncodingDocumentAttribute 的文档有点令人困惑:

NSNumber, containing an int specifying the NSStringEncoding for the file; for reading and writing plain text files and writing HTML; default for plain text is the default encoding; default for HTML is UTF-8.

所以,你的代码应该是:

NSString *html = @"“Hello” World";
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSMutableAttributedString *as =
[[NSMutableAttributedString alloc] initWithHTML:htmlData
options: options
documentAttributes:nil];

关于cocoa - NSAttributedString initWithHTML 字符编码不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15956698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com