2013-08-27 50 views
0
-(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 
     { 

     } 
.. 
.. 

回答

5

使用塊 - 這將是更容易處理:

[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

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

您正在使用異步URL連接與它代表一個NSURL連接。這就是方法3在方法2完成之前被觸發。爲了解決你的問題,使用這個

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

它應該肯定工作。