Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在后台线程中使用UIPasteboard可以吗?_Ios_Uipasteboard - Fatal编程技术网

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

Ios 在后台线程中使用UIPasteboard可以吗?,ios,uipasteboard,Ios,Uipasteboard,UIPasteboard线程安全吗 我正试着做这样的事情 dispatch_async(dispatch_get_global_queue(0, 0), ^{ UIPasteboard *generalPasteBoard = [UIPasteboard generalPasteboard]; NSData *settingsData = [generalPasteBoard dataForPasteboardType:@"SomeType"]; if (setti

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

您尝试在主线程之外使用它有什么特别的原因吗?在您给出的示例中,可以将UIPasteboard内容保留在主线程上,并且只在需要对其进行某些处理的点上进行异步调度。UIPasteboard不是线程安全的,因为它是一个UIKit类,我会小心一点,如果可能的话,不要从主线程接触它。一般来说,UIKit不是线程安全的,大多数UIKit工作必须在主线程上完成。读取pasteboard大约需要100毫秒,它会消耗我的一些冷启动时间。这就是为什么我想知道我是否可以把它扔到bg线程。也许我可以做一个dispatch\u async,然后在主线程上同步它?