Как преобразовать данные RTFD NSTextView в обычный текст в какао - PullRequest
4 голосов
/ 29 июня 2011

У меня есть один NSTextView, содержащий форматированный текст и встроенные изображения, как показано ниже.

NSTextView with formatted text and embedded image

Я хочу преобразовать вышеприведенный текст в обычный текст, как показано ниже:

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

Спасибо

1 Ответ

4 голосов
/ 29 июня 2011

После нескольких часов работы я нашел следующее решение для своих собственных требований. Пожалуйста, дайте мне знать, если у нас будет лучший способ сделать это.

Я создал категорию 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.

...