等待委托方法在ios中完成执行

问题描述:

-(void)method1 
     { 
      [self method2];  
      [self method3]; //After finishing execution of method2 and its delegates I want to execute method3 
     } 

这里method2在它调用时运行,但在它的委托方法执行之前,方法3开始执行。如何避免这种情况?任何建议或代码,请等待委托方法在ios中完成执行

我叫方法2

-(void)method2 
    { 
    .... 
     connection= [[NSURLConnection alloc] initWithRequest:req delegate:self ]; 
    .... 
    } 


    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 

     } 

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
     { 

     } 
.. 
.. 

使用块 - 这将是更容易处理:

[NSURLConnection sendAsynchronousRequest:request 
            queue:[[NSOperationQueue alloc] init] 

         completionHandler:^(NSURLResponse *response, 
              NSData *data, 
              NSError *error) 
{ 

    if ([data length] >0 && error == nil) { 
     // parse your data here 

     [self method3]; 

     dispatch_async(dispatch_get_main_queue(), ^{ 

       // call method on main thread, which can be used to update UI stuffs 
       [self updateUIOnMainThread]; 
     }); 
    } 
    else if (error != nil) { 
     // show an error 
    } 
}]; 
+0

+1这个,如果你能定位到iOS 5及更高版本。只要注意''completionHandler'块在后台线程/队列上被调用。 –

+1

@SteveWilford - 检查我更新的ans,在完成块中,添加一个块来调用主线程的方法。就像解析完成后,UI更新需要之后,就可以使用这种方法。 – Mrunal

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) 
{ 
    [self method3] 
} 

您正在使用异步URL连接与它代表一个NSURL连接。这就是方法3在方法2完成之前被触发。为了解决你的问题,使用这个

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    [self method3]; 
} 

它应该肯定工作。