objective-c - 等待方法在 iOS 中完成

标签 objective-c ios multithreading

我在 objective-c 中有两个类 Controller 和 Connector。 Controller 要求连接器建立与 Web 服务的连接以获取一些数据。连接本身是通过委托(delegate)实现的。如果数据到达,此委托(delegate)将获得方法调用。我将委托(delegate)设置为连接器本身。
我的问题是我希望 Controller 调用连接器上的一个方法,这个方法立即返回数据。这是没有授权的。
我尝试了多线程并在 Controller 中等待,但我只能找到一个方法的多线程:

[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:myClass withObject:nil];

单个方法的多线程是行不通的,因为无法调用Connector中的委托(delegate)方法,因为整个Connector类没有线程。谁能帮我解决这个问题?

编辑:我添加了调用连接器方法的代码(这是来自 Controller 的代码):
_data = nil;
dispatch_queue_t myQueue = dispatch_queue_create("my queue", NULL);
dispatch_async(myQueue, ^{
    _data = [_soapConnector startRequestWithSOAPMessage:soapMessage];
});

while(!_data){
    NSLog(@"waiting");
}
//data arrived successfully here so we can manipulate it

最佳答案

我认为你应该使用 block 。

在您的 Connector.h创建 completitionBlock属性(property)

@property (nonatomic,copy)void (^completitionBlock) (id obj, NSError * err);

在connector.m中不知道怎么连接webservice,这个例子是针对NSURLDelegate的

如果完成没问题
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

        if([self completitionBlock])
            [self completitionBlock](dataOK,nil);

 }
NSMutableData * dataOK是接收到的数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [dataOK appendData:data];
}

如果失败
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    if([self completitionBlock]) 
        [self completitionBlock](nil,error);   

}

然后从 Controller 类中调用连接器
[Connector getWebservice:^(id obj, NSError *err) {
        if (!err) {

            //Code executed when the webservice finish OK, obj will be the dataOK


        } else {

            //Code executed when the webservice return error
       }
    }];

关于objective-c - 等待方法在 iOS 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725611/

相关文章:

ios - 弹出键盘时禁用按钮

ios - 我怎样才能制作 -[NSURLCache cachedResponseForRequest :] work with redirected requests?

ios - HealthKit 计步器

c++ - 如何在不终止程序的情况下停止 std::thread 的运行

ios - GCD 在状态改变后将 block 添加到串行队列中

ios - UIImageView 中的 UISwipeGestureRecognizer

ios - Google map 实用程序 IOS Pod 错误

ios - 报告 UITableview reloadData 崩溃

c - 如何完成多个线程以多次加入一个进程? (pthread_mutex_lock)

c++ - 如何正确地从 shared_ptr 移动/读取