我希望能够从解析中检索图像,如下所示:
-(UIImage *) image {
__block NSData * imageData;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self.imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
imageData = data;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return [UIImage imageWithData:imageData];
}
但是由于该 block 是在邮件线程上执行的,并且信号量正在主线程上等待,因此该 block 永远不会被执行。我怎样才能重做我的代码?我需要能够返回没有完成 block 的图像,因为此方法是由我使用的库调用的。
最佳答案
您可以尝试使用GCD,在后台解析并加载,然后在主线程中使用图像。 代码可能如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = nil;
__block NSData *imageData;
[self.imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
imageData = data;
}];
image = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(), ^{
if (image) {
return image; // use your image here.
}
});
});
关于ios - 使用信号量从 Parse 返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20209150/