ios - 可以在后台线程中使用 UIPasteboard 吗?

标签 ios uipasteboard

UIPasteboard 线程安全吗?

我正在尝试做这样的事情

dispatch_async(dispatch_get_global_queue(0, 0), ^{
     UIPasteboard *generalPasteBoard = [UIPasteboard generalPasteboard];
     NSData *settingsData = [generalPasteBoard dataForPasteboardType:@"SomeType"];

    if (settingsData == nil) {

        UIPasteboard *pasteBoard = [UIPasteboard pasteboardWithName:@"SomeName" create:YES];
        settingsData = [pasteBoard dataForPasteboardType:@"SomeType"];
    }   
    // Do something with settingsData
});

这样做安全吗?我应该只在主线程上使用 UIPasteboard 吗?

最佳答案

我在 iOS 9 和 10 的后台线程上使用它没有任何问题。当粘贴板访问全局共享系统资源时,我认为它是线程安全的,即使它在 UIKit 框架中也是如此。显然没有文档支持我,只有我自己的经验。

示例代码,使用我为 MBProgressHUD 创建的类别:

typedef void (^ImageBlock)(UIImage* image);
#define DISPATCH_ASYNC_GLOBAL(code) dispatch_async(dispatch_get_global_queue(0, 0), ^{ code });
#define DISPATCH_ASYNC_MAIN(code) dispatch_async(dispatch_get_main_queue(), ^{ code });

+ (void) pasteboardImageWithCompletion:(ImageBlock)block
{
    // show hud in main window
    MBProgressHUD* hud = [MBProgressHUD showHUDAnimated:YES];
    DISPATCH_ASYNC_GLOBAL
    ({
        UIImage* img = [UIPasteboard generalPasteboard].image;
        if (img == nil)
        {
            NSURL* url = [UIPasteboard generalPasteboard].URL;
            if (url == nil)
            {
                NSData* data = [[UIPasteboard generalPasteboard] dataForPasteboardType:(NSString*)kUTTypeImage];
                img = [UIImage imageWithData:data];
            }
            else
            {
                img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            }
        }
        DISPATCH_ASYNC_MAIN
        ({
            block(img);
            [hud hideAnimated:YES];
        });
    });
}

关于ios - 可以在后台线程中使用 UIPasteboard 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538282/

相关文章:

ios - 从大照片生成图 block (iOS PhotoScroller)

ios - 获取当前时间转换为纪元时间

ios - 通知中心火 UIPasteboard 从 Safari 更改?

ios - 使用 NSManager 撤消剪贴板文本

objective-c - 将图像复制到粘贴板会将 jpeg 转码为 png

ios - 如何在 iOS 粘贴板中获取数据以保持多路访问

iOS SDK 在应用程序加载时获取剪贴板文本

ios - 验证 UITextField 中的电子邮件地址

ios - 接受函数的回调作为参数

ios - 更改 UITabBar 的色调/背景颜色