我在 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/