如何将NSTextView RTFD数据转换为可可中的纯文本

时间:2011-06-29 05:16:14

标签: nstextview nsattributedstring string-conversion

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

NSTextView with formatted text and embedded image

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

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

由于

1 个答案:

答案 0 :(得分:4)

经过几个小时的尝试后,我根据自己的要求提出了以下解决方案。如果我们能有更好的方法,请告诉我。

我使用以下代码创建了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。