In my NSString
, I've some accented characters and html tags, such as <i></i>
. I want to display them in NSTextField
with text attributes to them.
When I build the attrStr, I use:
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithHTML:[text dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSWebPreferencesDocumentOption : webPreferences}
documentAttributes:NULL];
I display the text as follow:
someTextField.attributedStringValue = attrStr;
But this require I know the encoding of the NSString
, but the problem is that I do not know the encoding. So how do I build an attribute string without knowing the encoding?
You don't need to know the encoding of your NSString
– it is an Objective-C string. The definition of dataUsingEncoding:
states, emphasis added:
Returns an
NSData
object containing a representation of the receiver encoded using a given encoding .
This method converts from whatever encoding NSString
uses internally into the specified encoding – so the result is your case is an NSData
containing the bytes of a UTF8 string.
If you are seeing invalid results maybe the issue is when you create the original NSString
?
HTH
Addendum I now see you asked this question first (I added an answer – basically you need to know or guess). Why are you reading the file into an NSString
in the first place? Just read it directly into an NSData
and then let the HTML parser sort it out (it will either read the HTML encoding tag or default to an encoding).
最终,我发现如果在上面使用NSUnicodeStringEncoding
,则重音字符将正确显示。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.