Можно ли сохранить (или восстановить) NSAttributedString, который содержит NSTextAttachment?

Я пишу текстовый редактор, с помощью которого пользователи могут вводить текст со стилями и вставлять изображения, поэтому я использую NSAttributedString для управления содержимым. Мой вопрос: как я могу сохранить содержимое до закрытия текстового редактора и восстановить содержимое после открытия редактора в следующий раз?

Я написал категорию NSAttributedString, прямо сейчас я могу хранить (и восстанавливать) текст, но не UIImageView в NSTextAttachment, ниже приведена часть моего кода:

-(NSData*)customEncode {
__block NSMutableArray* archivableAttributes=[[NSMutableArray alloc]init];

[self enumerateAttributesInRange:NSMakeRange(0, [self length]) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
    NSLog(@"range: %d %d",range.location, range.length);
    NSLog(@"dict: %@",attrs);
    NSLog(@"keys: %@", [attrs allKeys]);
    NSLog(@"values: %@", [attrs allValues]);

    NSMutableDictionary* tDict=[[NSMutableDictionary alloc]init];

    [tDict setObject:[NSNumber numberWithInt:range.location] forKey:@"location"];
    [tDict setObject:[NSNumber numberWithInt:range.length] forKey:@"length"];

    for (NSString* tKey in [attrs allKeys]) {
        if ([tKey isEqualToString:@"CTUnderlineColor"]) {
            [tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTUnderlineColor"])] forKey:@"CTUnderlineColor"];
        }
        if ([tKey isEqualToString:@"NSUnderline"]) {
            NSNumber* underline=[attrs objectForKey:@"NSUnderline"];
            [tDict setObject:underline forKey:@"NSUnderline"];
        }
        if ([tKey isEqualToString:@"CTForegroundColor"]) {
            [tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTForegroundColor"])] forKey:@"CTForegroundColor"];
        }
        if ([tKey isEqualToString:@"NSFont"]) {
            CTFontRef font=((__bridge CTFontRef)[attrs objectForKey:@"NSFont"]);

            NSDictionary* fontDict=[NSDictionary
                                    dictionaryWithObjects:
                                    [NSArray arrayWithObjects:(NSString*)CFBridgingRelease(CTFontCopyPostScriptName(font)),[NSNumber numberWithFloat:CTFontGetSize(font)], nil]
                                    forKeys:
                                    [NSArray arrayWithObjects:@"fontName", @"fontSize", nil]];

            [tDict setObject:fontDict forKey:@"NSFont"];
        }
    }

    [archivableAttributes addObject:tDict];
}];

NSMutableDictionary* archiveNSMString=[NSMutableDictionary
                                       dictionaryWithObjects: [NSArray arrayWithObjects:[self string],archivableAttributes,nil]
                                       forKeys:[NSArray arrayWithObjects:@"string",@"attributes",nil]];

NSLog(@"archivableAttributes array: %@",archiveNSMString);

NSData* tData=[NSKeyedArchiver archivedDataWithRootObject:archiveNSMString];

NSLog(@"tdata: %@",tData);

return tData;

}

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


person John Tai    schedule 07.04.2016    source источник


Ответы (3)


Наконец, я использовал подкласс NSKeyedArchiver с именем YYTextArchiver. для прямой сериализации NSAttributedString, и это сработало для меня.

person John Tai    schedule 07.04.2016

//Swift-3
You can store NSTextAttachment images by :-

var imageArray : [UIImage]


//MARKS:-  Extract attachedImage
    func textViewDidChange(_ textView: UITextView)  {
        imageArray = [UIImage]()
        let range = NSRange(location: 0, length: textView.attributedText.length)
        if (textView.textStorage.containsAttachments(in: range)) {
            let attrString = textView.attributedText
            var location = 0
            while location < range.length {
                var r = NSRange()
                let attrDictionary = attrString?.attributes(at: location, effectiveRange: &r)
                if attrDictionary != nil {
                    let attachment = attrDictionary![NSAttachmentAttributeName] as? NSTextAttachment
                    if attachment != nil {
                        if attachment!.image != nil {
                          //store the image Attached to it.
                          imageArray.append( attachment!.image!)
                        }
                    }
                    location += r.length
                }
            }
        }
    }

}

Concat все вышеприведенное изображение, прикрепленное к нему: -

let axtractedImageAttribute = NSMutableAttributedString()
        for image in imageArray {
            let attachment:NSTextAttachment = NSTextAttachment()
            attachment.image = image
            attachment.setImageHeight(height: 20)
            let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment)
            axtractedImageAttribute.append(attachmentString)
        }

Демо

person Shrawan    schedule 30.12.2016

Используйте fileWrapperFromRange:documentAttributes:error: с типом документа NSRTFDTextDocumentType.

person rob mayoff    schedule 07.04.2016
comment
Я не знаком с NSFileWrapper, можете ли вы предоставить более подробную информацию или ссылку? благодарю вас. - person John Tai; 07.04.2016