从NSAttributedString中的nsfilewrapper / nstextattachment获取文件名和路径

时间:2012-02-04 03:41:20

标签: cocoa nstextview nsattributedstring nsfilewrapper nstextattachment

我有一个基本的NSTextView,启用了丰富的文本和图形(在IB中)。我想得到的是拖入的任何图像的路径和文件名,因此我可以将它们传递给另一个类。

我是NSAttributedString的新手,但我使用enumerateAttributesInRange:options:usingBlock:寻找NSAttachmentAttributeName的循环,这一切都正常。但是进一步深入,我进入了fileWrapper类,它是apparent inability to give me the path of the item

我如何获取NSTextAttachment的名称和路径?

相关:是否有更简单的方法来获取它们然后单步执行属性?

非常感谢!

1 个答案:

答案 0 :(得分:8)

虽然我个人蔑视NSFileWrapper的设计,但如果您只需要每个附件的数据,您可以通过NSFileWrapper的regularFileContents方法将其作为NSData实例访问。但是,我需要一个有效且明确的路径名来指向我的应用程序的附件。要做到这一点比应该做的要多得多:

您可以继承NSTextView并覆盖NSDraggingDestination Protocol方法draggingEntered:,并且可以在拖动操作期间遍历传递给应用程序的NSPasteboardItem对象。我选择将路径名及其inode编号保存在NSMutableDictionary中,因为NSFileWrapper可以为您提供引用文件的inode。稍后,当我通过NSAttributedString访问NSTextView内容时,我可以使用inode作为索引来获取附件的路径名。

- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender {

    // get pasteboard from dragging operation

    NSPasteboard *pasteboard = [sender draggingPasteboard];

    NSArray *pasteboardItems = [pasteboard pasteboardItems];

    for ( NSPasteboardItem *pasteboardItem in pasteboardItems ) {

        // look for a file url type from the pasteboard item

        NSString *draggedURLString = [pasteboardItem stringForType:@"public.file-url"];

        if (draggedURLString != nil) {

            NSURL *draggedURL = [NSURL URLWithString:draggedURLString];

            NSString *draggedPath = [draggedURL path];

            NSLog(@"pathname: %@", draggedPath);

            // do something with the path

            // get file attributes

            NSDictionary *draggedAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:draggedPath error:nil];

            if ( draggedAttributes == nil)
                continue;

            // the NSFileWrapper allows access to the absolute file via NSFileSystemFileNumber
            // put the path and the inode (returned as an NSNumber) into a NSMutableDictionary 

            NSNumber *draggedInode = [draggedAttributes objectForKey:NSFileSystemFileNumber];

            [draggedFiles setObject:draggedPath forKey:draggedInode];
        }

    }

    return [super draggingEntered:sender];
}

我的解决方案的一个问题,即不影响我的应用程序,是多个文件被拖入视图(单独或一起),这些文件是同一文件的硬链接,只会被编入索引作为添加到的最后一个路径名共享inode的字典。根据应用程序如何使用路径名,这可能是一个问题。