如何让块中的代码先执行

时间:2016-05-05 08:57:50

标签: ios objective-c iphone multithreading

-(UIImage *)getImageFromURL:(NSURL *)imageURL{
    __block UIImage *image = [UIImage new];
    PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
    PHAsset *asset = result.firstObject;
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        image = result;
    }];
    return image;
}

块“image = result”中的代码在代码块“返回图像”之后执行,因此它总是返回nil。 如何让块中的代码先执行。使用线程或NSOperation或GCD?

1 个答案:

答案 0 :(得分:0)

-(UIImage *)getImageFromURL:(NSURL *)imageURL{
     __block UIImage *image = [UIImage new];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
        PHAsset *asset = result.firstObject;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            image = result;
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
             return image;
        });
    });
}