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

Here method2 got running when it called but before execution of its delegate methods the method3 got started to execute. How to avoid that? Any suggestion or code please

I called a nsurl connection with its delegates in method 2

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


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

        }

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

        }
..
..
Dolo
  • 966
  • 14
  • 28

3 Answers3

5

Use blocks - it would be easier to handle:

[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
     }
 }];
Mrunal
  • 13,982
  • 6
  • 52
  • 96
  • +1 for this if you can target iOS 5 and higher. Just be aware that the `completionHandler` block is invoked on a background thread/queue. – Steve Wilford Aug 27 '13 at 15:34
  • 1
    @SteveWilford - Check my updated ans, where in completion block, added a block to call method on main thread. Like after parsing is done and after that UI update requires then this mehodology can be used. – Mrunal Aug 28 '13 at 07:07
1
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) 
{
    [self method3]
}
Injectios
  • 2,777
  • 1
  • 30
  • 50
0

You are using Asynchronous Url Connection. Thats y method 3 is getting triggered before the method 2 completes. To solve your issue, Use this

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

It should definitely work.

Mani Kandan
  • 629
  • 4
  • 12