【问题标题】:Getting filename and path from nsfilewrapper / nstextattachment in NSAttributedString从 NSAttributedString 中的 nsfilewrapper / nstextattachment 获取文件名和路径
【发布时间】:2012-02-26 15:15:15
【问题描述】:

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

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

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

相关:有没有更简单的方法来获取它们然后逐步遍历属性?

非常感谢!

【问题讨论】:

  • 不幸的是 NSFileWrapper 返回的属性字典也没有提供完整的路径名。 NSFileWrapper 的设计通过拒绝提供对原始引用对象的路径名的访问来做出短视和不幸的封装假设。

标签: cocoa nstextview nsattributedstring nsfilewrapper nstextattachment


【解决方案1】:

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

您可以继承您的 NSTextView 并覆盖 NSDraggingDestination 协议方法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 的字典。根据您的应用程序使用路径名的方式,这可能是个问题。

【讨论】:

  • 很酷,但很糟糕。在调查这个问题时,我假设 draggingEntered 是我要去的地方,但还没有写下代码。我会在接下来的几天里尝试你的例子并让你知道。谢谢!
  • 这似乎是唯一的出路。感谢您的代码示例 - 它让我到达了我需要去的地方。接受了这个答案。
猜你喜欢
  • 1970-01-01
  • 2017-04-15
  • 2011-11-16
  • 2012-01-21
  • 2012-10-25
  • 2023-03-26
  • 1970-01-01
  • 2016-02-02
相关资源
最近更新 更多