gpt4 book ai didi

nstextview - 如何在 cocoa 中将 NSTextView RTFD 数据转换为纯文本

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

我有一个包含格式化文本和嵌入图像的 NSTextView,如下所示。

NSTextView with formatted text and embedded image

我想将上面转换为纯文本,如下所示:

Hi this is test data (...picture...)This is colored text.

谢谢

最佳答案

尝试了几个小时后,我根据自己的要求提出了以下解决方案。请告诉我我们是否有更好的方法来做到这一点。

我使用以下代码创建了 NSString 类别:

+ (NSString *)plainTextFromRTFD:(NSTextStorage *)aTextStorage 
attachmentString:(NSString *)aString {

NSString *returnString = @"";

//Default value of aString, If nil
if (aString == nil) {
aString = @"(...Attachment...)";
}

if (aTextStorage && aString) {

//Initialize NSMutableString object to hold plain text
NSMutableString *plainText = [[NSMutableString alloc] init];

//Loop through all the attributes one-by-one to identify the NSAttachment
for(int i =0;i<[aTextStorage length];i++) {

NSDictionary *attr= [aTextStorage attributesAtIndex:i effectiveRange:NULL];

//Check whether attribute contains NSAttachment or not
if ([attr objectForKey:@"NSAttachment"] != nil) {
//Replace NSTextAttachment with attachmentString value
[plainText appendFormat:@"%@",aString];
} else {
//Add character to plain text
[plainText appendFormat:@"%@",[[[aTextStorage characters] objectAtIndex:i] string]];
}
}

//copy NSString from NSMutableString
returnString = [plainText copy];

//release NSMutableString
[plainText release];
}

return [returnString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];}

而且,我正在使用它,如下所示:
NSLog(@"%@",[NSString plainTextFromRTFD:[contentView textStorage] attachmentString:nil]);

其中 contentView 是 NSTextView。

关于nstextview - 如何在 cocoa 中将 NSTextView RTFD 数据转换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6516052/

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