Search code examples
iosdispatch-async

performSelectorOnMainThread calling a selector on another viewcontroller


the following code is working just fine:

   NSURL* urlAddressJSonUrl = [NSURL URLWithString:urlString];
        dispatch_async(globalQueue,
                       ^{
                           NSData *imageData = [NSData dataWithContentsOfURL:urlAddressJSonUrl];

                           [self performSelectorOnMainThread:@selector(setImage:)
                                                  withObject:[UIImage imageWithData:imageData] waitUntilDone:NO];
                       });

since I need to call it from different viewControllers I want place it in a general class that has public global help function (+) so I'm looking for a way to pass the selector and the target as parameters for performSelectorOnMainThread to run with


Solution

  • You implied that you have the target. Why don't you just call it with the target?

    NSURL* urlAddressJSonUrl = [NSURL URLWithString:urlString];
    dispatch_async(globalQueue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:urlAddressJSonUrl];
    
       [target performSelectorOnMainThread:@selector(setImage:)
                                withObject:[UIImage imageWithData:imageData]
                             waitUntilDone:NO];
    });
    

    Or better

    NSURL* urlAddressJSonUrl = [NSURL URLWithString:urlString];
    dispatch_async(globalQueue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:urlAddressJSonUrl];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [target setImage:[UIImage imageWithData:imageData]];
        });
    });