Saving NSAttributedString with NSTextAttachment into file. How to?

人盡茶涼 提交于 2019-12-09 07:14:28

问题


I have a NSTextView, which may contains rich text or rich text with image as NSTextAttachment. There is how I adds attachment:

NSImage *image = [NSImage imageNamed:@"image"];

NSTextAttachmentCell *attachmentCell =[[NSTextAttachmentCell alloc] initImageCell:image];
NSTextAttachment *attachment =[[NSTextAttachment alloc] init];
[attachment setAttachmentCell: attachmentCell ];
NSAttributedString *attributedString =[NSAttributedString  attributedStringWithAttachment: attachment];
[[aTextView textStorage] beginEditing];
if ([aTextView shouldChangeTextInRange:NSMakeRange([aTextView selectedRange].location, 0) replacementString:@""]) {
    [[aTextView textStorage] insertAttributedString:attributedString atIndex:[aTextView selectedRange].location];
    [aTextView didChangeText];
}
[[aTextView textStorage] endEditing];

My -fileWrapperOfType:error: method:

- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
{
    NSRange documentRange = NSMakeRange(0, [[[WindowController aTextView] textStorage] length]);
    NSTextStorage *text = [[WindowController aTextView] textStorage];

    NSFileWrapper *resultWrapper = nil;
    if ([typeName compare:@"public.rtf"] == NSOrderedSame) {
        resultWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:[text RTFFromRange:documentRange documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:NSRTFTextDocumentType, NSDocumentTypeDocumentAttribute, nil]]];
    }
    else if ([typeName compare:@"com.apple.rtfd"] == NSOrderedSame) {
        resultWrapper = [text RTFDFileWrapperFromRange:documentRange documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:NSRTFDTextDocumentType, NSDocumentTypeDocumentAttribute, nil]];
    }
    return resultWrapper;
}

But when I'm saving RTFD, all attachments looses. Please, help. What I'm missing?


回答1:


I have found an acceptable solution, it's described here: Cocoa: custom attachment in a text view



来源:https://stackoverflow.com/questions/11204929/saving-nsattributedstring-with-nstextattachment-into-file-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!