ios - 等到委托(delegate)方法在 ios 中完成执行

标签 ios objective-c multithreading nsurlconnectiondelegate

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

此处,方法 2 在调用时开始运行,但在执行其委托(delegate)方法之前,方法 3 开始执行。如何避免这种情况?任何建议或代码请

我在方法 2

中调用了一个与其委托(delegate)的 nsurl 连接
 -(void)method2
    {
    ....
       connection= [[NSURLConnection alloc] initWithRequest:req delegate:self ];
    ....
    }


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

        }

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

        }
..
..

最佳答案

使用 block - 会更容易处理:

[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
     }
 }];

关于ios - 等到委托(delegate)方法在 ios 中完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459161/

相关文章:

java - Java 中的递归感知线程池?

javascript - 用户单击提交时等待指示器

ios - 如何在Xcode中调用带参数的url

ios - 用于验证 API 的 OAuth2 - 无法重定向回我的应用程序

objective-c - 如何在我的 OSX 应用程序中运行嵌入式二进制文件?

c# - 多线程机制可从winforms代码运行一些冗长的操作,并与GUI进行通信

ios - 如何在 SwiftUI 预览中打印?

iphone - 不使用核心数据对 TableViewCell 进行编号

objective-c - 插入语句不适用于sqlite3 iPhone中的同一数据库上的第二个表

c - 多线程程序由于参数而出现段错误