我有一个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); }
解决方法
>枚举附件. [NSTextStorage enumerateAttribute:…]
>获取附件的文件包装器.
>写一个URL.
>获取附件的文件包装器.
>写一个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 }];