首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在从main函数返回值之前等待委托函数完成

如何在从main函数返回值之前等待委托函数完成
EN

Stack Overflow用户
提问于 2019-09-05 17:47:44
回答 1查看 168关注 0票数 0

我有一个用于捕获真实深度相机信息的自定义函数,该函数在代理函数完成对捕获的照片的处理之前返回。在返回正确的值之前,我需要以某种方式等待,直到所有委托都完成。

我尝试将main函数调用包装到一个同步块中,但这并没有解决问题。

代码语言:javascript
复制
- (NSDictionary *)capture:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject
{
  if (@available(iOS 11.1, *)) {
      // Set photosettings to capture depth data
      AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey : AVVideoCodecJPEG}];
      photoSettings.depthDataDeliveryEnabled = true;
      photoSettings.depthDataFiltered = false;
      @synchronized(self) {
          [self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
      }
  }
  // Somehow need to wait here until the delegate functions finish before returning
  return self.res;
}

调用太晚的委托函数:

代码语言:javascript
复制
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
{
  Cam *camera = [[Cam alloc] init];
  self.res = [camera extractDepthInfo:photo];
}

目前,在调用委托之前返回nil,只有在调用之后,委托函数才会将所需的结果分配给self.res

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-05 18:29:21

我相信你要找的就是dispatch_semaphore_t

信号量允许您锁定线程,直到执行第二个操作。这样,您可以推迟方法的返回,直到委托返回(如果您在辅助线程上操作)。

这种方法的问题是,您将锁定线程!因此,如果你在主线程中操作,你的应用程序将变得无响应。

我建议您考虑将响应移动到完成块,类似于:

代码语言:javascript
复制
-(void)capture:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject completion:(void (^)(NSDicitionary* ))completion {
    self.completion = completion
    ...
}

并在末尾调用补全:

代码语言:javascript
复制
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
{
  Cam *camera = [[Cam alloc] init];
  self.res = [camera extractDepthInfo:photo];
  self.completion(self.res);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57802760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档