mohkhan
mohkhan

Reputation: 12315

Is it ok to use UIPasteboard in a background thread?

Is UIPasteboard thread safe ?

I am trying to do something like this

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

Is this safe to do or should I use UIPasteboard only on the main thread ?

Upvotes: 3

Views: 1562

Answers (1)

jjxtra
jjxtra

Reputation: 21140

I'm using it on a background thread on iOS 9 and 10 with no issues. As the pasteboard accesses global, shared system resources, I would assume it to be thread safe, even though it is in the UIKit framework. Obviously there is no documentation to back me up, just my own experience.

Example code, using a category I created for 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];
        });
    });
}

Upvotes: 1

Related Questions