更新:
这真的只适用于 RTF,而不是 RTFD。也就是说,如果[ns containsAttachments]
,最后可能无法创建rtfString
。
您可以在创建 RTFD 时指定一些选项以使其采用 UTF8 编码。
这段代码对我们来说效果很好(尽管我们正在使用属性列表序列化):
NSAttributedString *ns = ...;
NSError *error = nil;
NSString *rtfString = nil;
NSData *rtfdData = [ns dataFromRange:NSMakeRange(0, [ns length])
documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
NSRTFDTextDocumentType, NSDocumentTypeDocumentOption,
[NSNumber numberWithInt:NSUTF8StringEncoding], NSCharacterEncodingDocumentAttribute,
nil]
error:&error];
if (error == nil) {
rtfString = [[[NSString alloc] initWithData: rtfdData encoding:NSUTF8StringEncoding] autorelease];
}
然后,writer.Write(rtfString);