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

时间:2015-05-29 20:13:06

标签: ios uipasteboard

UIPasteboard线程安全吗?

我正在尝试做这样的事情

String modified = symbole(test);

这样做是否安全或者我应该只在主线程上使用UIPasteboard?

1 个答案:

答案 0 :(得分:0)

我在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];
        });
    });
}