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?
发布于 2017-05-06 22:36:25
我在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];
});
});
}https://stackoverflow.com/questions/30538282
复制相似问题