如何从NSAttributedString获取图像数据

joe*_*els 9 cocoa nsattributedstring

我有一个NSTextView.我将图像粘贴到其中并查看.当我获得文本视图的NSAttributedString的NSTextAttachment时,它的文件包装器是nil.如何获取粘贴到文本视图中的图像数据?

我在NSAttributedString上使用类别来获取文本附件.如果可能的话,我宁愿不写入磁盘.

- (NSArray *)allAttachments
{
    NSError *error = NULL;
    NSMutableArray *theAttachments = [NSMutableArray array];
    NSRange theStringRange = NSMakeRange(0, [self length]);
    if (theStringRange.length > 0)
    {
        NSUInteger N = 0;
        do
        {
            NSRange theEffectiveRange;
            NSDictionary *theAttributes = [self attributesAtIndex:N longestEffectiveRange:&theEffectiveRange inRange:theStringRange];
            NSTextAttachment *theAttachment = [theAttributes objectForKey:NSAttachmentAttributeName];
            if (theAttachment != NULL){
                NSLog(@"filewrapper: %@", theAttachment.fileWrapper);
                [theAttachments addObject:theAttachment];
            }
            N = theEffectiveRange.location + theEffectiveRange.length;
        }
        while (N < theStringRange.length);
    }
    return(theAttachments);
}
Run Code Online (Sandbox Code Playgroud)

小智 9

  1. 枚举附件.[NSTextStorage enumerateAttribute:...]
  2. 获取附件的文件包装器.
  3. 写入URL.

    [textStorage enumerateAttribute:NSAttachmentAttributeName
                            inRange:NSMakeRange(0, textStorage.length)
                            options:0
                         usingBlock:^(id value, NSRange range, BOOL *stop)
     {
         NSTextAttachment* attachment = (NSTextAttachment*)value;
         NSFileWrapper* attachmentWrapper = attachment.fileWrapper;
         [attachmentWrapper writeToURL:outputURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil];
         (*stop) = YES; // stop so we only write the first attachment
     }];
    
    Run Code Online (Sandbox Code Playgroud)

此示例代码仅将第一个附件写入outputURL.