Objective C - 如何从NSAttributedString创建rtf

4

我可以使用以下方法将 RTF 字符串转换为属性字符串:

 NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];

现在我怎样才能将attributedString转换回rtf字符串?

如果没有相应的方法,那么我怀疑你是否能够做到。 - trojanfoe
1个回答

15
您想使用-dataFromRange:documentAttributes:error:。
NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"YOLO" attributes:nil];
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} error:NULL];
[data writeToFile:@"/me.rtf" atomically:YES];

当然,你可能希望拥有一些属性而不是“YOLO”,但你明白了。

此外,如果你想简单地将其写入磁盘,那么fileWrapperFromRange:documentAttributes:error:甚至可能是一个更好的选择。有关从Attribute String编程指南中读取和写入更多信息。


我使用了NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSRTFTextDocumentType ,NSDocumentTypeDocumentAttribute, nil]; NSData *rtfData = [txtView.attributedText dataFromRange:NSMakeRange(0, txtView.attributedText.length) documentAttributes:documentAttributes error:NULL]; NSString *rtfString = [[NSString alloc] initWithData:rtfData encoding:NSUTF8StringEncoding]; - Hassy
感谢您的帮助 :) - Hassy
1
@ghazi_jaffary 这就是我在这里的原因。 - Lucas Derraugh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接