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/