开发者

RTFString Containing NSASCIIStringEncoding Special Characters?

I have a string in my cocoa GUI that needs to have special formatting (fonts, colors, etc.). Naturally, I'm using an attributed string. For convenience, I Init the string as an RTF:

NSString *inputString = @"This string has special characters";
NSString *rtfString =开发者_如何学JAVA [NSString stringWithFormat:@"{@"***LENGTHY RTF FORMATTING STRING *** %@", inputString];
NSAttributedString *testString = [[NSAttributedString alloc] initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];

The problem is, the "inputString" might have special characters, which are not displayed properly due to the UTF8Encoding. They're replaced with other symbols. é is left as Å©.

So, right now I'm doing this:

NSData* intermediateDataString=[inputString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

inputString = [[[NSString alloc] initWithData:intermediateDataString encoding:NSUTF8StringEncoding] autorelease];

This does not display the unexpected characters, but it does remove all accents and leaves in their stead the unaccented letter - é is left as e.

This is an improvement since everything can be read, but it is far from ideal.

Thoughts?


I would do something like this. First, create a dummy attributed string:

NSString *dummyRTFString = @"***LENGTHY RTF FORMATTING STRING *** A";
NSAttributedString *dummyAS = [[NSAttributedString alloc] 
                                      initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding] 
                               documentAttributes:nil];

and obtain the attributes:

NSDictionary*attributes=[dummyAS attributesAtIndex:0 effectiveRange:NULL];
[dummyAS release];

Now I will use this attribute to create another attributed string:

NSAttributedString* as=[[NSAttributedString alloc] initWithString:inputString attributes:attributes];

Another approach is to use HTML instead of RTF; then you can include non-ascii characters as unicode in it.


In your first line of code, I assume that's really @"This string has special characters" otherwise you'd get a compile error. And it looks like your second line has an extra @".

If you know you're using UTF-8, why say NSASCIIStringEncoding?

Really, you should put the RTF including the string with special characters in a resource, not embedded in your code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜