performSelectorOnMainThread在另一个viewcontroller上调用选择器

时间:2014-02-04 02:03:13

标签: ios dispatch-async

以下代码工作得很好:

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

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

因为我需要从不同的viewControllers调用它我想把它放在一个具有公共全局帮助函数(+)的通用类中所以我正在寻找一种方法来传递选择器和目标作为performSelectorOnMainThread运行的参数与

1 个答案:

答案 0 :(得分:2)

你暗示你有目标。你为什么不用目标调用它?

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

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

或更好

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

    dispatch_async(dispatch_get_main_queue(), ^{
        [target setImage:[UIImage imageWithData:imageData]];
    });
});