【问题标题】:Copy the complete content of general NSPasteboard复制通用NSPasteboard的完整内容
【发布时间】:2016-10-12 03:20:03
【问题描述】:

我需要将general NSPasteboard的完整内容复制到指定名称的粘贴板上。我试过这段代码:

- (void)copyFromGeneralPasteboard {
NSMutableArray *archive = [[NSMutableArray alloc] init];
NSArray *typeArray = [[NSPasteboard generalPasteboard] types];
NSPasteboard *myPasteboard = [NSPasteboard pasteboardWithName:@"SpecialPb"];
[myPasteboard declareTypes:typeArray owner:self];

for (NSPasteboardItem *item in [[NSPasteboard generalPasteboard] pasteboardItems])
{
    NSPasteboardItem *archivedItem = [[NSPasteboardItem alloc] init];
    for (NSString *type in [item types])
    {
        NSData *data=[[item dataForType:type] mutableCopy];
        if (data) {
            [archivedItem setData:data forType:type];
        }
    }
    [archive addObject:archivedItem];
}
[[NSPasteboard generalPasteboard] clearContents];
[myPasteboard writeObjects:archive];
[archive removeAllObjects];}

我正在使用此代码进行检查。

- (void)SendToGeneralPasteboard {
NSMutableArray *archive = [[NSMutableArray alloc] init];
for (NSPasteboardItem *item in [[NSPasteboard pasteboardWithName:@"SpecialPb"] pasteboardItems])
{
    NSPasteboardItem *archivedItem = [[NSPasteboardItem alloc] init];
    for (NSString *type in [item types])
    {
        NSData *data=[[item dataForType:type] mutableCopy];
        if (data) {
            [archivedItem setData:data forType:type];
        }
    }
    [archive addObject:archivedItem];
}
[[NSPasteboard generalPasteboard] writeObjects:archive];}

因此,我使用 IWork Pages 进行了测试,它适用于文本和属性文本。但是,当我尝试使用文本和图像运行时,程序只是复制并粘贴文本。此外,我尝试只使用图像运行,它也可以。 您能告诉我如何将我的代码用于任何类型的数据吗?谢谢。

【问题讨论】:

  • 只是一个想法:你不能myPasteboard.pasteboardItems = [NSPasteboard generalPasteboard].pasteboardItems吗?
  • 谢谢。但是pasteboardItems 是只读的。
  • 嗯,是的,愚蠢的想法。

标签: xcode macos cocoa nspasteboard


【解决方案1】:

我意识到这是一个老问题,但我今天正在处理类似的问题,所以我想我会回答这个问题,以防其他人在寻找。

由于您只是想将完整的内容从一个粘贴板复制到另一个粘贴板,因此无需使用 NSPasteboardItem。只需在一个粘贴板上迭代所有键入的数据并将其写入另一个。 Swift 中的简洁示例:

func copyItemsFromPasteboard(_ fromPasteboard: NSPasteboard, toPasteboard: NSPasteboard) {
    for thisType in generalPB.types ?? [] {
        let thisData = generalPB.data(forType: thisType) ?? Data()
        toPasteboard.setData(thisData, forType: thisType)
    }
}

let generalPB = NSPasteboard(name: .generalPboard)
let customPB = NSPasteboard(name: NSPasteboard.Name(rawValue: "com.example.custom"))

copyItemsFromPasteboard(generalPB, toPasteboard: customPB)

我希望这对某人有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多